Home  >  Article  >  Java  >  How to Ensure Proper Content-Type Encoding in Spring MVC @ResponseBody Responses?

How to Ensure Proper Content-Type Encoding in Spring MVC @ResponseBody Responses?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 20:19:01288browse

How to Ensure Proper Content-Type Encoding in Spring MVC @ResponseBody Responses?

Setting Response Content-Type in Spring MVC via @ResponseBody

When developing with Spring MVC and the @ResponseBody annotation, it's important to control the content-type of the response. In one instance, a user encountered an issue where the response was displaying with ISO-8859-1 encoding instead of the desired UTF-8, despite explicitly setting the content-type to UTF-8 in the controller method.

Solution

To resolve this issue, the user discovered that the @ResponseBody annotation itself supports specifying the content-type through the produces attribute. By adding the following line to the controller method, they were able to explicitly define the content-type of the response:

<code class="java">@RequestMapping(value = "ajax/gethelp")
@ResponseBody(produces = "text/plain; charset=UTF-8")
public String handleGetHelp(Locale loc, String code, HttpServletResponse response) {
    // ...
}</code>

This configuration allows the controller method to return a plain text response with UTF-8 encoding, as intended.

Additional Notes

For users utilizing Spring 3.1 and above, the @ResponseBody annotation provides a more straightforward approach for setting the response content-type compared to using a custom converter strategy.

The above is the detailed content of How to Ensure Proper Content-Type Encoding in Spring MVC @ResponseBody Responses?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn