Spring 解决编码问题-CharacterEncodingFilter

来源:互联网 发布:华为和高通的差距 知乎 编辑:程序博客网 时间:2024/05/21 15:02

项目中经常会遇到编码问题,Spring框架给我们提供过滤器CharacterEncodingFilter来解决编码问题。

1、结构:

详解Spring中的CharacterEncodingFilter【原】
可以看到其继承GenericFilterBean和OncePerRequestFilter,也就是说,这个过滤器就是针对于每次浏览器请求进行过滤的,然后再其之上添加了父类没有的功能即处理字符编码。

2.官方解释:

Servlet 2.3/2.4 Filter that allows one to specify a character encoding for requests. This is useful because current browsers typically do not set a character encoding even if specified in the HTML page or form. (这句话就说你在html页面或表单中设置编码是没有用的)

This filter can either apply its encoding if the request does not already specify an encoding, or enforce this filter's encoding in any case ("forceEncoding"="true").(只要你设置了foreEncoding=true,则在代码中设置编码格式没用,)In the latter case, the encoding will also be applied as default response encoding on Servlet 2.4+ containers (although this will usually be overridden by a full content type set in the view).

 

3.如何使用

下面来看看如何在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>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>

 其中encoding用来设置编码格式,forceEncoding用来设置是否理会 request.getCharacterEncoding()方法,设置为true则强制覆盖之前的编码格式。

 

4.源码赏析

详解Spring中的CharacterEncodingFilter【原】

当Servlet容器启动的时候,会读取web.xml中对于过滤器的配置信息, 读取到<init-param>中的子标签<param-name>encoding和forceEncoding所对应的<param-value>的值,再通过调用该类setEncoding(String encoding)和setForceEncoding(boolean forceEncoding) 将值注入到这连个字段中。
详解Spring中的CharacterEncodingFilter【原】

在这里就能看到为什么设置foreEncoding为true会覆盖掉request.getCharacterEncoding()中的方法了吧,呵呵,还是那句话,源码之前了无秘密,只有深入到源代码之中才能看清本质。

本文出自“foyuanchina”博客,请务必保留此出处http://blog.sina.com.cn/s/blog_92b93d6f0100ypp9.html 

0 0
原创粉丝点击