昨天在做项目的时候用@ResponseBody注解,发现返回页面上的中文是乱码,解决过程也是让我很郁闷!!!特此记录一些。目前有下面几种解决方案:
@RequestMapping的produces方法
第一种解决方案是使用@RequestMapping注解的produces方法。写法如下:
@RequestMapping(value = "testPersonalValidtor.do",produces = "application/json;charset=utf-8")
在方法上加上这个注解就可以了。但是这样写的话有限制,只能在特定的方法上面使用。如果需要全局都使用的话,需要修改SpringMVC的配置文件。
使用messageConverters
第二种解决办法是使用HttpMessageConverter接口的相关实现类。我们先看配置文件中的配置信息。
<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>
昨天让我郁闷的是,我这样配置了之后确依然是不生效。后来才发现是位置放的不对,需要把这段配置放到<mvc:annotation-driven />的上面。真是很无语的感觉!!!
注意:一定要放到<mvc:annotation-driven />的上面,否则不会生效。
并且需要在Maven依赖中配置上Jackjson的依赖。
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>