How to set content-length in Spring MVC REST for JSON?

ruslanys picture ruslanys · Jun 11, 2014 · Viewed 18k times · Source

I have some code:

@RequestMapping(value = "/products/get", method = RequestMethod.GET)
public @ResponseBody List<Product> getProducts(@RequestParam(required = true, value = "category_id") Long categoryId) {
    // some code here
    return new ArrayList<>();
}

How could I configure Spring MVC (or MappingJackson2HttpMessageConverter.class) to set right header Content-Length by default? Because now my response header content-length equal to -1.

Answer

Woody Sun picture Woody Sun · Dec 16, 2015

You can add ShallowEtagHeaderFilter to filter chain. The following snippet works for me.

import java.util.Arrays;

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterBean = new FilterRegistrationBean();
        filterBean.setFilter(new ShallowEtagHeaderFilter());
        filterBean.setUrlPatterns(Arrays.asList("*"));
        return filterBean;
    }

}

The response body will looks like the below:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
X-Application-Context: application:sxp:8090
ETag: "05e7d49208ba5db71c04d5c926f91f382"
Content-Type: application/json;charset=UTF-8
Content-Length: 232
Date: Wed, 16 Dec 2015 06:53:09 GMT