Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsebody encoding in Spring MVC 4.3.3

To set @responsebody encoding in spring-webmvc, I used to add the following lines in configuration file:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/plain;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
        <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
    </mvc:message-converters>

This override the default charset responsebody handler use. And it worked with spring-mvc version 4.2.7 and below.

However, in the latest version of spring-webmvc(4.3.3), this method does not work. In the new version, StringHttpMessageConverter reads content-type from response header, and if content-type string includes charset information, it use this charset and ignores it's default charset.

I know I can write like this to solve this problem:

@RequestMapping(value = "/getDealers", method = RequestMethod.GET, 
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {

}

But I have to write it on every method or every controller. Is there any way to set responsebody encoding globally like I did before?

like image 657
易天明 Avatar asked Oct 18 '16 02:10

易天明


1 Answers

I find that I didn't add <value>application/json;charset=UTF-8</value> in my configuration. I don't know why my old configuration works with version 4.2.7 and below, but this new configuration just works with version 4.3.3:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/plain;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
        </bean>
        <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
   </mvc:message-converters>

like image 94
易天明 Avatar answered Nov 06 '22 00:11

易天明