Home  >  Article  >  Java  >  How can I control the content type of the response with @ResponseBody in Spring MVC?

How can I control the content type of the response with @ResponseBody in Spring MVC?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 05:13:30283browse

How can I control the content type of the response with @ResponseBody in Spring MVC?

@ResponseBody Attribute: Controlling Response Content-Type in Spring MVC

In Spring MVC, the @ResponseBody annotation plays a crucial role in determining the content type of the response sent back to the client. This annotation is useful when returning custom responses, such as JSON or plain text, in a flexible manner.

In your case, you're encountering an issue where the response from your controller method is being set with an incorrect content-encoding. This is due to the default behavior of Spring MVC, which falls back to the ISO-8859-1 encoding if it doesn't find a suitable converter for the returned value.

To resolve this problem and set the correct content type, you can utilize the produces attribute of the @ResponseBody annotation. This attribute allows you to specify the media types (i.e., content types) that your controller method can produce.

For your specific case, you want your controller method to produce plain text in UTF-8 encoding. Here's how you can achieve this:

<code class="java">@RequestMapping(value = "ajax/gethelp")
@ResponseBody
public String handleGetHelp(Locale loc, String code) {
    log.debug("Getting help for code: " + code);
    String help = messageSource.getMessage(code, null, loc);
    log.debug("Help is: " + help);
    return help;
}</code>

By adding produces = "text/plain; charset=utf-8" to the @ResponseBody annotation, you're instructing Spring MVC to explicitly set the content type of the response to text/plain with a character set of utf-8. This should ensure that the response is encoded correctly and displayed properly on the client side.

Note that the @RequestMapping annotation also supports the produces attribute, which can be used to control the media types that the corresponding request mapping can handle.

The above is the detailed content of How can I control the content type of the response with @ResponseBody in Spring MVC?. 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