16

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.

ruslanys
  • 1,183
  • 2
  • 13
  • 25

2 Answers2

16

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
Woody Sun
  • 359
  • 3
  • 5
  • `org.springframework.boot.context.embedded.FilterRegistrationBean` is deprecated as of 1.4 in favor of `org.springframework.boot.web.servlet.FilterRegistrationBean` – Rafael Membrives Jul 12 '21 at 11:25
4

The following filter in chain sets content-length:

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.util.ContentCachingResponseWrapper;

public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,     FilterChain chain) throws IOException, ServletException {

        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);

        chain.doFilter(request, responseWrapper);

        responseWrapper.copyBodyToResponse();

    }

    @Override
    public void destroy() {
    }

}

The main idea that all content is cached in ContentCachingResponseWrapper and finally content-length is set when you call copyBodyToResponse().