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设置的编码类型,是否有优先级的说法?


慕标琳琳
浏览 423回答 1
1回答

DIEA

@RequestBody 既然使用到这个注解,那就说明楼主使用的不是get方法。参数不在URL中那自然是不需要使用URLEncoding.encode的吧。<init-param>&nbsp;&nbsp;&nbsp; &nbsp;<param-name>encoding</param-name>&nbsp;&nbsp;&nbsp; &nbsp;<param-value>UTF-8</param-value>&nbsp;&nbsp;</init-param>&nbsp;&nbsp;你这里设置了编码就足够了。@Overrideprotected void doFilterInternal(&nbsp; &nbsp; &nbsp; &nbsp; HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)&nbsp; &nbsp; &nbsp; &nbsp; throws ServletException, IOException {&nbsp; &nbsp; if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {&nbsp; &nbsp; &nbsp; &nbsp; request.setCharacterEncoding(this.encoding);&nbsp; &nbsp; &nbsp; &nbsp; if (this.forceEncoding) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response.setCharacterEncoding(this.encoding);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; filterChain.doFilter(request, response);}forceEncoding 为 true 为设置response的编码,并不会对request参数造成影响。楼主仔细看一下CharacterEncodingFilter执行的过程,以及Filter执行的先后顺序。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java