Resolving Content-Type Discrepancies with Spring MVC's @ResponseBody
In Spring MVC applications, when a controller method returns a String and is annotated with @ResponseBody, the framework is responsible for setting the response's content-type. By default, it uses "text/plain" with UTF-8 encoding.
Customizing the Content-Type
To override the default content-type, you can include the following configuration in your Spring application:
<code class="xml"><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/plain;charset=UTF-8" /> </bean> </list> </property> </bean></code>
This will ensure that strings returned from @ResponseBody methods use the specified content-type. However, this approach is not always effective.
Using the Produces Attribute
Spring 3.1 introduces the produces attribute to the RequestMapping annotation. By specifying produces = "application/json; charset=utf-8", you can explicitly set the content-type for the response.
Example Controller:
<code class="java">@RequestMapping(value = "/getDealers", method = RequestMethod.GET, produces = "application/json; charset=utf-8") @ResponseBody public String sendMobileData() { return "..."; }</code>
This approach uses the produces attribute to override the default content-type behavior and ensure that the response contains the correct encoding.
The above is the detailed content of How to Resolve Content-Type Discrepancies with Spring MVC\'s @ResponseBody?. For more information, please follow other related articles on the PHP Chinese website!