2014-06-11 19 views
13

Mam kod:Jak ustawić długość treści w Spring MVC REST dla 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<>(); 
} 

Jak mogę skonfigurować wiosny MVC (lub MappingJackson2HttpMessageConverter.class), aby ustawić właściwą nagłówka Content-Length domyślnie? Ponieważ teraz mój nagłówek odpowiedzi content-length jest równy -1.

+2

Możesz sprawdzić to http://forketyfork.blogspot.com/2013/06/how-to-return-file-stream- or-classpath.html – shazin

+0

@shazin Dziękuję. To nie jest złe rozwiązanie. To działa!) – ruslanys

Odpowiedz

10

Możesz dodać ShallowEtagHeaderFilter do filtrowania łańcucha. Poniższy fragment działa dla mnie.

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

} 

Wola ciało reakcja wygląda następująco:

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

Poniższy filtr w zestawach łańcuchowych Content-Length:

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

} 

Główną ideą, że wszystkie treści są buforowane w ContentCachingResponseWrapper i na końcu długość treści jest ustawiana, gdy wywołujemy metodę copyBodyToResponse().

Powiązane problemy