Home > Java > javaTutorial > body text

How can I customize the Content-Type of a response in Spring MVC using @ResponseBody?

DDD
Release: 2024-11-01 05:15:01
Original
693 people have browsed it

How can I customize the Content-Type of a response in Spring MVC using @ResponseBody?

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";
}
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!