SpringMVC的GET/POST中文参数乱码解决

今天用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”);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值