您的位置:首页 > 其它

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

2017-03-17 13:40 267 查看
 
前提:

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“);
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  POST GET 汉字乱码