乱码问题的解决

来源:互联网 发布:人工智能 安防 编辑:程序博客网 时间:2024/04/25 02:54

一、web中文乱码问题
1.请求乱码
请求由浏览器发送给服务器
浏览器编码:浏览器编码的字符集有HTML页面决定,具体有HTML页面中的meta标签决定
服务器解码:服务器默认的字符集是ISO-8859-1
由于两者的字符集不一致所以导致乱码
解决方案:
对于POST请求
      request.setCharacterEncoding("utf-8");
            该操作一定要在第一次获取请求参数之前
   对于GET请求 
      由于get请求的请求参数在地址栏中,在到达Servlet之前已经被服务器进行解码,所以在Servlet里使用POST请求的方式设置字符集就不管用了。
      这个时候我们需要改变服务器URL解码的字符集,在server.xml文件中的Connector标签中添加URIEncoding="UTF-8"
     <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
2.响应乱码
响应由服务发送给浏览器
服务器编码:服务器默认的字符集是ISO-8859-1
浏览器解码:浏览器解码默认的字符集是GBK
解决方案,通过以下两种方式告诉浏览器使用UTF-8字符集进行解码:
          方式一:
          response.setHeader("Content-Type", "text/html;charset=utf-8");
          方式二:
          response.setContentType("text/html;charset=UTF-8");
      • 设置了响应头之后浏览器就会使用设置的字符集进行解码,同时在Servlet中也会使用该字符集进行编码

二、SpringMVC中CharacterEncodingFilter原理

get请求乱码设置服务器URIEncoding="UTF-8"

@Override
    protectedvoiddoFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throwsServletException, IOException {
        if(this.encoding!=null&& (this.forceEncoding|| request.getCharacterEncoding() == null)) {
               //根据filter配置的encoding值,设置请求编码方式,解决post请求乱码
            request.setCharacterEncoding(this.encoding);
            if(this.forceEncoding) {
               //forceEncoding设置响应编码,解决响应乱码,页面内容("Content-Type")在渲染视图由SpringMVC设置
                response.setCharacterEncoding(this.encoding);
            }
        }
        filterChain.doFilter(request, response);
    }

三、请求传中文

get请求:

<a href="${contextPath}/hello?name=哈喽>哈喽</a>,直接用request.getParameter得到的字符串name将会乱码,这也是因为GET方式是用httpurl传过来的默认用iso-8859-1编码的,所以首先得到的name要再用iso-8859-1编码得到原文后,再进行用utf-8(看具体页面的charset是什么utf-8gbk)进行解码即可。

              String name=new String(request.getParameter("name").getBytes("ISO8859-1"),"utf-8");

四、数据库



0 0