首先中文乱码可以分为两种情况:
一种是request传进来的时候就是中文乱码,比方说:当使用get方式,直接在地址栏中拼中文,传入后台是发生乱码,这样一般有两种解决方式:
一种是在前台传进来时,使用encodeURI(encodeURI(“中文”)),在后台使用URLDecoder.decode(request.getParameter(“yy”),”utf-8″))来解码,至于为什么前台需要使用两次encodeURI可以参考这篇文章为什么要两次调用encodeURI来解决乱码问题(PS:遇到的情况,自己本地测试时,自己的tomcat默认使用的字符集为UTF-8,然而线上的tomcat使用的是ISO-8859-1,导致线上数据显示出现了bug 🙁 )
另一种就是直接改tomcat的默认字符集,直接修改tomcat的service.xml内容
修改前内容:
<Connector port="8080" protocol="HTTP/1.1"
maxThreads="150" connectionTimeout="200000"
redirecPort="8443"/>
修改后内容:
<Connector port="8080" protocol="HTTP/1.1"
maxThreads="150" connectionTimeout="200000"
redirecPort="8443" URIEncoding="utf-8"/>
(ps:个人推荐这种,一劳永逸 🙂 )
另一种是response传出去的时候就是中文乱码也是有两种常见的方式:
一种是在RequestMapping注解中添加 produces = “application/json; charset=utf-8″,不过需要注意的是,produces这个属性只有在spring mvc 3.1及以上才有,3.0版本是没有的。并且需要在方法上添加@ResponseBody注解。
另一种是直接在spring配置文件中添加
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
需要在扫描包component-scan的前面,最好就直接放在声明后面就完事了。
ps:老的spring项目,遇到的中文乱码问题,怀念springboot一分钟。