org.springframework.web.filter.CharacterEncodingFilter详解

   很简单很实用的一个过滤器,当前台JSP页面和Java代码中使用了不同的字符集进行编码的时候就会出现表单提交的数据或者上传/下载中文名称文件出现乱码的问题,那这个类就可以出场了。

web.xml中配置如下:

  1. <filter>  
  2.         <filter-name>Set UTF-8</filter-name>  
  3.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  4.         <init-param>  
  5.             <param-name>encoding</param-name>  
  6.             <param-value>utf-8</param-value>  
  7.         </init-param>  
  8.     </filter>  
  9.     <filter-mapping>  
  10.         <filter-name>Set UTF-8</filter-name>  
  11.         <url-pattern>/*</url-pattern>  
  12.     </filter-mapping>  
设置编码为utf-8;还有一个参数 forceEncoding------->当request中已经被指定了一个字符集的时候是否再将用endcoding对应的字符集设置到request中去。默认为false,意思是当request中指定了编码方式,则不适用用encoding指定的编码方式。

CharacterEncodingFilter中的过滤方法如下:

  1. @Override  
  2.     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)  
  3.         throws ServletException, IOException {<span style="white-space:pre">  
  4. </span><pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 28px;">               //当指定了encoding,且forceEncoding为false ,同时request中没有制定编码方式事,设置request和response的编码方式为encoding所指定的编码方式  
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {request.setCharacterEncoding(this.encoding);if (this.forceEncoding) {response.setCharacterEncoding(this.encoding);}}filterChain.doFilter(request, response);}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值