POST和GET请求的汉字乱码问题

 

前提:

jsp页面中:  

 <metahttp-equiv="content-type" content="text/html;charset=UTF-8">通知浏览器以utf-8解码

GET请求传递原理:

get请求编码方式和post请求提交编码方式不同,get是把数据直接放到url中,例如以上的uname,IE浏览器先对中文进行utf-8编码(一个中文3个字符表示 太长),继而为了缩短字符又用ISO8859-1编码后传递给服务器。服务器的doGet方法中要先进行ISO8859-1解码再utf-8解码才能看到中文。

乱码解决方法:

方法一:

 

修改Tomcat/conf/server.xml配置:

指定get请求编码方式:URIEncoding="UTF-8"

<Connector port="8080"protocol="HTTP/1.1"

              connectionTimeout="20000"

              redirectPort="8443" URIEncoding="UTF-8"/>

   <!--上面接口中添加URIEncoding="UTF-8"解决get乱码问题

      A"Connector" using the shared thread pool-->

方法二:

 

使用String name = newString(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");进行重新编码

方法三:

 

处理后的URL不在是通过一次 encodeURI()转换后的字串“%8B%E8%AF%95”,而是经过上一步两层encodeURI()处理URL处理后字符串”%25258B%25E8%AF%2595”通过再次编码原有被浏览起解析为转义字符的”%“被再次编码,转换成了普通字符转”%25“。encodeURI()实际上就是使用utf-8格式进行转化的

使用:

URLDecoder.decode("chinese string","UTF-8") 

 

POST请求传递原理:

post请求在浏览器端把数据以utf-8的形式存储到http的请求体中,不用通过url传输,继而只要request.setCharacterEncoding("utf-8");通知request以utf-8形式解码就行,因为request默认以ISO8859-1进行解码的。

乱码解决方法:

方法一:

在action中使用request解析是设置编码格式为utf-8

Request.setCharacterEncode(“utf-8“);

 

方法二:

使用spring中提供的编码过滤器

在web.xml中配置:

<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>

 

其中在web.xml中配置过滤器进行过滤编码:其实这里的过滤器底层实现也是:

request.setCharacterEncode(“utf-8“);

response.setCharacterEncode(“utf-8“);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值