当时用@ResponseBody返回中文字符串时会出现乱码的情况:
这是由于SpringMVC默认的处理字符集是ISO-8859-1,此格式无法标识中文字符。而StringHttpMessageConverter向客户端写回字符串时会添加Content-Type的响应头,在没有指定字符集的情况下采用默认的字符集即ISO-8859-1,如果返回的是中文就会产生乱码。
解决方法:
将默认处理字符集改为utf-8格式,具体操作为在spring-mvc.xml中进行以下配置:
<!-- mvc注解驱动 -->
<mvc:annotation-driven>
<!-- 转换字符编码,springmvc默认为ISO-8859-1 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="#{T(java.nio.charset.Charset).forName('UTF-8')}"/>
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>applicaiton/javascript;charset=UTF-8</value>
</list>
</property>
<property name="writeAcceptCharset"><value>false</value></property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
其中将writeAcceptCharset设置为false,即可看到响应头清爽很多,节省资源。
也可通过注解设置局部的字符编码:
@RequestMapping(value = "/demo1",produces = {"application/json;charset=utf-8"})
或
@RequestMapping(value = "/demo1",produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"})
测试可见不再出现乱码: