2014-06-11 27 views
13

Bazı kod var:JSON için Spring MVC REST'de içerik uzunluğu nasıl ayarlanır?

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

nasıl Spring MVC (veya MappingJackson2HttpMessageConverter.class) varsayılan olarak sağ başlık Content-Length ayarlamak yapılandırabilirsiniz? Çünkü şimdi yanıt başlığım content-length -1'e eşit.

+2

Bu http://forketyfork.blogspot.com/2013/06/how-to-return-file-stream-or-classpath.html – shazin

+0

@ shazin adresini incelemek isteyebilirsiniz. Teşekkür ederiz. Kötü bir çözüm değil. Bu çalışıyor!) – ruslanys

cevap

10

Filtre zincirine ShallowEtagHeaderFilter ekleyebilirsiniz. Aşağıdaki snippet benim için çalışıyor.

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

} 

tepki vücut irade aşağıda benziyor: zincir setleri içerik uzunlukta içinde

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

Aşağıdaki filtre:

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üm içerik ContentCachingResponseWrapper önbelleğe olduğunu ana fikri ve sonunda copyBodyToResponse() öğesini çağırdığınızda içerik uzunluğu ayarlanır.

İlgili konular