Customizing Response Content-Type in Spring MVC with @ResponseBody
In Spring MVC, the @ResponseBody annotation automatically adds the Content-Type header to the HTTP response. However, the default Content-Type is "application/json". To customize the Content-Type for a specific method, you can use the produces attribute of the @RequestMapping annotation.
For example, if you want to return a plain text response with UTF-8 encoding, you can use the following controller method:
@RequestMapping(value = "/gethelp", method = RequestMethod.GET, produces = "text/plain; charset=UTF-8") public @ResponseBody String handleGetHelp() { return "Some help text"; }
In this example, the produces attribute specifies that the gethelp method will produce a plain text response with UTF-8 encoding.
Note: Make sure the StringHttpMessageConverter is registered as a message converter in your Spring configuration. This can be done by adding the following bean:
<bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/plain; charset=UTF-8" /> </bean>
The above is the detailed content of How can I customize the Content-Type of a response in Spring MVC using @ResponseBody?. For more information, please follow other related articles on the PHP Chinese website!