Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set content-length in Spring MVC REST for JSON?

I have some code:

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

How could I configure Spring MVC (or MappingJackson2HttpMessageConverter.class) to set right header Content-Length by default? Because now my response header content-length equal to -1.

like image 412
ruslanys Avatar asked Jun 11 '14 06:06

ruslanys


People also ask

How do I set the content length in Java?

To manually pass the Content-Length header, you need to add the Content-Length: [length] and Content-Type: [mime type] headers to your request, which describe the size and type of data in the body of the POST request.

Can we use REST controller in Spring MVC?

Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.

How do I change the response type dynamically in spring REST?

So, by setting the default response content type to "application/json", any request with no Accept header will be serviced in JSON while the consumer will have to add an Accept: "application/xml" to have the response type as xml.

How pass JSON object in post request in spring boot?

Send JSON Data in POST Spring provides a straightforward way to send JSON data via POST requests. The built-in @RequestBody annotation can automatically deserialize the JSON data encapsulated in the request body into a particular model object. In general, we don't have to parse the request body ourselves.


1 Answers

You can add ShallowEtagHeaderFilter to filter chain. The following snippet works for me.

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

}

The response body will looks like the below:

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
like image 55
Woody Sun Avatar answered Sep 19 '22 12:09

Woody Sun