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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With