2014-06-11 16 views
13

Tôi có một số mã:Cách đặt độ dài nội dung trong Spring MVC REST cho JSON?

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

Làm thế nào tôi có thể cấu hình Spring MVC (hoặc MappingJackson2HttpMessageConverter.class) để thiết lập đúng tiêu đề Content-Length theo mặc định? Vì bây giờ tiêu đề phản hồi của tôi là content-length bằng -1.

+2

Bạn có thể muốn kiểm tra http://forketyfork.blogspot.com/2013/06/how-to-return-file-stream-or-classpath.html – shazin

+0

@shazin Cảm ơn bạn. Nó không phải là một giải pháp tồi. Nó hoạt động!) – ruslanys

Trả lời

10

Bạn có thể thêm ShallowEtagHeaderFilter vào chuỗi bộ lọc. Đoạn mã sau hoạt động cho tôi.

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

} 

Cơ thể phản ứng sẽ trông giống như dưới đây:

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 
4

bộ lọc sau trong bộ chuỗi nội dung dài:

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

} 

Ý tưởng chính là tất cả các nội dung được lưu trữ trong ContentCachingResponseWrapper và cuối cùng là chiều dài nội dung được đặt khi bạn gọi copyBodyToResponse().

Các vấn đề liên quan