Java 如何在Spring MVC REST for JSON中设置内容长度?

Java 如何在Spring MVC REST for JSON中设置内容长度?,java,json,spring,spring-mvc,content-length,Java,Json,Spring,Spring Mvc,Content Length,我有一些代码: @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&

我有一些代码:

@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<>();
}
@RequestMapping(value=“/products/get”,method=RequestMethod.get)
public@ResponseBody List getProducts(@RequestParam(required=true,value=“category\u id”)长类别id){
//这里有一些代码
返回新的ArrayList();
}

默认情况下,如何配置SpringMVC(或MappingJackson2HttpMessageConverter.class)来设置正确的标题内容长度?因为现在我的响应头
内容长度
等于-1

您可以将ShallowEtagHeaderFilter添加到过滤器链中。下面的代码片段适合我

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;
    }

}
响应主体将如下所示:

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

链中的以下过滤器设置内容长度:

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() {
    }

}

主要思想是所有内容都缓存在ContentCachingResponseRapper中,最后在调用copyBodyToResponse()时设置内容长度

你可能想看看这个@shazin谢谢。这是一个不错的解决方案。它的工作!)