Spring-web源码解析之Filter-CharacterEncodingFilter

基于4.1.7.RELEASE


在web.xml我们经常看见这么一段

<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,下面我们就来看看CharacterEncodingFilter的源码,首先看看类图


CharacterEncodingFilter并不是直接实现Filter接口,而是继承了OncePerRequestFilter,其作用稍后再讲。

CharacterEncodingFilter含有两个属性,一个是在web.xml中经常出现的encoding,它指明了用于设置request的encoding的值

另一个是foreceEncoding,默认为false,如果设置为true它就会使encoding属性强制替换掉request中的encoding值,而不管request获取的encoding是否为空。

下面看其主要的方法

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

上面说过encoding是设置request的编码,而这个方法就是具体实现过程。如果设置了forceEncoding,还会同时将response的默认编码设置为encoding。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值