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

2022-09-03 06:30:19

我有一些代码:

@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<>();
}

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


答案 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

答案 2

链中的以下筛选器设置内容长度:

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

}

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