在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-8</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-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean>
值得一提的是,@ResponseBody注解是通过在spring-mvc.xml中配置的 <mvc:annotation-driven></mvc:annotation-driven>来启用的,所以上述bean必须写在 <mvc:annotation-driven></mvc:annotation-driven>的前边,否则是不起作用的。
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/11477.html