今天用springMVC接收前台get参数时,发现到Controller的是乱码,网上查了资料总结一下MVC的乱码问题:
POST请求参数中文乱码:
产生原因:
spring MVC中默认的编码格式为“ISO-8859-1”,因此造成乱码。
解决:
在web.xml中配置Spring字符过滤器
<!--配置解决中文乱码的过滤器-->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但是这只能解决POST请求的乱码,并不能解决GET请求乱码
GET请求参数中文乱码:
产生原因:
解决方案也很简单,除了平常在项目中web.xml里配置的转码filter,jsp跟代码文件统一编码外,最关键的一点就是在Tomcat的conf目录下的server.xml中配置 Connector的URIEconding=“UTF-8"属性即可。
官方文档中对这个属性的说明:
*
URIEncoding :This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.
*
这里参考文档是Tomcat5.5的,亲测对Tomcat7也管用。
也就是在tomcat的conf/server.xml文件里将原配置:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"/>
改为
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
或者 useBodyEncodingForURI="true"同时也加上
但亲测无效,所以GET中文参数乱码原因未知,请各位大佬赐教
解决方法:
String中的带参构造方法
将传入的参数重新编码
new String(接收到的参数.getBytes(“ISO-8859-1”), “UTF-8”);