关于responseBody注解中文乱码的问题解决

在web.xml中定义字符集过滤器:

<filter>
<filter-name>SpringEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SpringEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

如果这样仍然不起作用,则需要在spring-mvc.xml中配置如下bean:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=utf-</value>
<value>text/html;charset=UTF-</value>
</list>
</property>
</bean>
</list>
</property>
</bean>

值得一提的是,@ResponseBody注解是通过在spring-mvc.xml中配置的 <mvc:annotation-driven></mvc:annotation-driven>来启用的,所以上述bean必须写在 <mvc:annotation-driven></mvc:annotation-driven>的前边,否则是不起作用的。

上一篇:Nginx设置websocek代理服务


下一篇:@ResponseBody注解