Home > Java > javaTutorial > body text

How to Resolve Content-Type Discrepancies with Spring MVC\'s @ResponseBody?

DDD
Release: 2024-10-30 01:26:28
Original
766 people have browsed it

How to Resolve Content-Type Discrepancies with Spring MVC's @ResponseBody?

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

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

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!

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!