项目中经常会遇到编码问题,Spring框架给我们提供过滤器CharacterEncodingFilter来解决编码问题。
1、结构:
可以看到其继承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中配置:
4.源码赏析
当Servlet容器启动的时候,会读取web.xml中对于过滤器的配置信息,
在这里就能看到为什么设置foreEncoding为true会覆盖掉request.getCharacterEncoding()中的方法了吧,呵呵,还是那句话,源码之前了无秘密,只有深入到源代码之中才能看清本质。