Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestController produces charset=UTF-8

Since updating to the latest version of Spring-Boot (1.4.1) I've noticed that in my RestControllers even though I'm explicitly setting the media type produced to "application/json" it is now producing "application/json;charset=UTF-8"

Controller:

@RestController
@RequestMapping(value = "/api/1/accounts", consumes = "application/json", produces = "application/json")
public class AccountController {
.....

Response Header

Content-Type →application/json;charset=UTF-8

Is there now somewhere else where this is configured which is overriding the RequestMapping setting?

like image 790
Bacon Avatar asked Sep 30 '16 09:09

Bacon


People also ask

What is @RestController made of?

@RestController annotation is a special controller used in RESTful Web services, and it's the combination of @Controller and @ResponseBody annotation. It is a specialized version of @Component annotation. It is a specialized version of @Controller annotation. In @Controller, we can return a view in Spring Web MVC.

How does a RestController work internally?

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.

What is the scope of RestController?

@RestController annotation declares a Spring @Component whose scope is by default SINGLETON . This is documented in the @Scope annotation: Defaults to an empty string ("") which implies SCOPE_SINGLETON. This means that it will be the same instance of TestController that will handle every requests.

Can RestController return view?

@RestController is not meant to be used to return views to be resolved. It is supposed to return data which will be written to the body of the response, hence the inclusion of @ResponseBody .


1 Answers

As per OrangeDog's comment above the MappingJackson2HttpMessageConverter handles the charset. This has been updated recently to add the default charSet if none is specified in message (i.e. via the RequestMapping produces config)

This can be overridden by implementing the below bean and setting the charSet to null:

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    jsonConverter.setObjectMapper(objectMapper);
    jsonConverter.setDefaultCharset(null);
    return jsonConverter;
}
like image 145
Bacon Avatar answered Sep 30 '22 17:09

Bacon