willjava

导航

 

 

<filter>
    <filter-name>encodingFilter</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>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

 

用于解决POST方式造成的中文乱码问题,编码只能被指定一次,即如果客户端设置了编码,则过滤器不会再设置

 

如果是GET,需要修改 Tomcat根式目录的 conf/server.xml文件中,找<Connector port="tomcat端口" />,在里面加URIEncoding="utf-8"

 

参数乱码分析:

 

  提交表单时request与response对象encoding与contentType的值情况

  1. 使用JQuery的$.ajax提交表单时:
    GET默认:
      request encoding null
      request contentType null
      response encoding ISO-8859-1
      response contentType null
    POST默认:
      request encoding UTF-8
      request contentType application/x-www-form-urlencoded; charset=UTF-8
      response encoding ISO-8859-1
      response contentType null


  2. 使用form提交表单时:
    GET默认:
      request encoding null
      request contentType null
      response encoding ISO-8859-1
      response contentType null
    POST默认:
      request encoding null
      request contentType application/x-www-form-urlencoded
      response encoding ISO-8859-1
      response contentType null

  • 对POST提交而言,jquery的ajax提交request的encoding为UTF-8,所以能正确获取值;但通过普通form提交,request的encoding为null,不转码的话获取参数为乱码。

 

  • request.setCharacterEncoding("UTF-8") 这个方法也就对post提交的有效果,对于get提交和上传文件时的enctype="multipart/form-data"是无效的

 

  • 如果使用get方式提交中文,接受参数的页面也会出现乱码,这个乱码的原因也是tomcat的内部编码格式iso8859-1导致。Tomcat会以get的缺省编码方式iso8859-1对汉字进行编码,编码后追加到url,导致接受页面得到的参数为乱码,解决方法:

    • String str = new String(request.getParameter("something").getBytes("ISO-8859-1"),"utf-8")

    • 修改 Tomcat根式目录的 conf/server.xml文件中,找<Connector port="tomcat端口" />,在里面加URIEncoding="utf-8"

 

Spring CharacterEncodingFilter代码分析

属性:

private String encoding;
private boolean forceEncoding = false; 

主代码:   

protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

    if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
        request.setCharacterEncoding(this.encoding);
        if (this.forceEncoding) {
            response.setCharacterEncoding(this.encoding);
        }
    }
    filterChain.doFilter(request, response);
} 

 

posted on 2014-03-28 23:53  威尔爪哇  阅读(216)  评论(0)    收藏  举报