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

rus*_*nys 13 java spring json 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<>();
}
Run Code Online (Sandbox Code Playgroud)

我如何配置Spring MVC(或MappingJackson2HttpMessageConverter.class)来默认设置正确的标题Content-Length?因为现在我的响应标头content-length等于-1.

Woo*_*Sun 11

您可以添加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;
    }

}
Run Code Online (Sandbox Code Playgroud)

响应正文如下所示:

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
Run Code Online (Sandbox Code Playgroud)