Home  >  Q&A  >  body text

java - CharacterEncodingFilter 类

使用org.springframework.web.filter.CharacterEncodingFilter配置请求编码方式,使用@RequestBody接受ajax的application/json;charset=utf-8 传输中文乱码,配置如下

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

疑问:使用String data = URLEncoding.encode('数据',ISO-8859-1);
再URLDecode.decode(data,utf-8);即可得到正确的中文数据,我理解为tomcat将请求按照默认的编码ISO-8859-1来解析了,确实我也没有设置tomcat的默认编码格式,但是我同个项目的其它非ajax请求中文正常,猜测可能是CharacterEncodingFilter配置的没有拦截到我的请求,前辈帮忙看看哪里配置错了。还有个问题就是tomcat设置的默认编码类型和CharacterEncodingFilter设置的编码类型,是否有优先级的说法?

黄舟黄舟2763 days ago788

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-18 09:52:24

    @RequestBody 既然使用到这个注解,那就说明楼主使用的不是get方法。参数不在URL中那自然是不需要使用URLEncoding.encodeYes.

    <init-param>  
       <param-name>encoding</param-name>  
       <param-value>UTF-8</param-value>  
    </init-param>  

    It is enough that you set the encoding here.


    @Override
    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);
    }

    forceEncodingtrue 为设置response的编码,并不会对requestParameters have an impact.

    The host please take a closer look at the order of execution. CharacterEncodingFilter执行的过程,以及Filter

    reply
    0
  • Cancelreply