一、Filter简介
Filter也称之为过滤器,它是Servlet技术中最激动人心的技术之一,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp,Servlet, 静态图片文件或静态html文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,Filter接口源代码:
[java] view plain copy
- public abstract interface Filter{
- public abstract void init(FilterConfig paramFilterConfig) throws ServletException;
- public abstract void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain
- paramFilterChain) throws IOException, ServletException;
- public abstract void destroy();
- }
二、Filter是如何实现拦截的?(Filter的工作原理)
Filter接口中有一个doFilter方法,当我们编写好Filter,并配置对哪个web资源进行拦截后,WEB服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可达到如下目的:
调用目标资源之前,让一段代码执行。
是否调用目标资源(即是否让用户访问web资源)。
调用目标资源之后,让一段代码执行。
web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则web资源不会被访问。
三、Filter开发流程
3.1、Filter开发步骤
Filter开发分为2步:
* 编写java类实现Filter接口,并实现其doFilter方法。
* 在web.xml 文件中使用<filter>和<filter-mapping>元素对编写的filter类进行注册,并设置它所能拦截的资源。
过滤器范例:
[java] view plain copy
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- /**
- * @author yangcq
- * @description 过滤器Filter的工作原理
- */
- public class FilterTest implements Filter{
- public void destroy() {
- System.out.println("----Filter销毁----");
- }
- public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
- // 对request、response进行一些预处理
- request.setCharacterEncoding("UTF-8");
- response.setCharacterEncoding("UTF-8");
- response.setContentType("text/html;charset=UTF-8");
- System.out.println("----调用service之前执行一段代码----");
- filterChain.doFilter(request, response); // 执行目标资源,放行
- System.out.println("----调用service之后执行一段代码----");
- }
- public void init(FilterConfig arg0) throws ServletException {
- System.out.println("----Filter初始化----");
- }
- }
在web. xml中配置过滤器:
[html] view plain copy
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="3.0"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <!--配置过滤器-->
- <filter>
- <filter-name>FilterTest</filter-name>
- <filter-class>com.yangcq.filter.FilterTest</filter-class>
- </filter>
- <!--映射过滤器-->
- <filter-mapping>
- <filter-name>FilterTest</filter-name>
- <!--“/*”表示拦截所有的请求 -->
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
3.2、Filter链
在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。
四,Spring框架下,过滤器的配置
如果项目中使用了Spring框架,那么,很多过滤器都不用自己来写了,Spring为我们写好了一些常用的过滤器。下面我们就以字符编码的
过滤器CharacterEncodingFilter为例,来看一下Spring框架下,如果配置过滤器。
[html] view plain copy
- <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>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
很简单吧,这样几行配置代码,就完成了从全局控制字符编码的功能。接下来,我们看一下CharacterEncodingFilter这个过滤器的关键代码,感受一下,大师的风采,如果我们写过滤器的话,可以以此为范例。
[java] view plain copy
- package org.springframework.web.filter;
- import java.io.IOException;
- import javax.servlet.FilterChain;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.util.ClassUtils;
- public class CharacterEncodingFilter extends OncePerRequestFilter{
- private static final boolean responseSetCharacterEncodingAvailable = ClassUtils.hasMethod(
- class$javax$servlet$http$HttpServletResponse, "setCharacterEncoding", new Class[] { String.class });
- // 需要设置的编码方式,为了支持可配置,Spring把编码方式设置成了一个变量
- private String encoding;
- // 是否强制使用统一编码,也是为了支持可配置
- private boolean forceEncoding;
- // 构造器,在这里,Spring把forceEncoding的值默认设置成了false
- public CharacterEncodingFilter(){
- this.forceEncoding = false;
- }
- // encoding/forceEncoding的setter方法
- public void setEncoding(String encoding){
- this.encoding = encoding;
- }
- public void setForceEncoding(boolean forceEncoding){
- this.forceEncoding = forceEncoding;
- }
- // Spring通过GenericFilterBean抽象类,对Filter接口进行了整合,
- 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) && (responseSetCharacterEncodingAvailable)) {
- response.setCharacterEncoding(this.encoding);
- }
- }
- filterChain.doFilter(request, response);
- }
- }
GenericFilterBean类:
public abstract class GenericFilterBean implements Filter, BeanNameAware, ServletContextAware, InitializingBean, DisposableBean
还没有过瘾,那就再看一个项目中使用过的一个过滤器:InvilidCharacterFilter(防止脚本攻击的过滤器)
[java] view plain copy
- import java.io.IOException;
- import java.util.Enumeration;
- import javax.servlet.FilterChain;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.web.filter.CharacterEncodingFilter;
- /*
- * InvalidCharacterFilter:过滤request请求中的非法字符,防止脚本攻击
- * InvalidCharacterFilter继承了Spring框架的CharacterEncodingFilter过滤器,当然,我们也可以自己实现这样一个过滤器
- */
- public class InvalidCharacterFilter extends CharacterEncodingFilter{
- // 需要过滤的非法字符
- private static String[] invalidCharacter = new String[]{
- "script","select","insert","document","window","function",
- "delete","update","prompt","alert","create","alter",
- "drop","iframe","link","where","replace","function","onabort",
- "onactivate","onafterprint","onafterupdate","onbeforeactivate",
- "onbeforecopy","onbeforecut","onbeforedeactivateonfocus",
- "onkeydown","onkeypress","onkeyup","onload",
- "expression","applet","layer","ilayeditfocus","onbeforepaste",
- "onbeforeprint","onbeforeunload","onbeforeupdate",
- "onblur","onbounce","oncellchange","oncontextmenu",
- "oncontrolselect","oncopy","oncut","ondataavailable",
- "ondatasetchanged","ondatasetcomplete","ondeactivate",
- "ondrag","ondrop","onerror","onfilterchange","onfinish","onhelp",
- "onlayoutcomplete","onlosecapture","onmouse","ote",
- "onpropertychange","onreadystatechange","onreset","onresize",
- "onresizeend","onresizestart","onrow","onscroll",
- "onselect","onstaronsubmit","onunload","IMgsrc","infarction"
- };
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws ServletException, IOException{
- String parameterName = null;
- String parameterValue = null;
- // 获取请求的参数
- @SuppressWarnings("unchecked")
- Enumeration<String> allParameter = request.getParameterNames();
- while(allParameter.hasMoreElements()){
- parameterName = allParameter.nextElement();
- parameterValue = request.getParameter(parameterName);
- if(null != parameterValue){
- for(String str : invalidCharacter){
- if (StringUtils.containsIgnoreCase(parameterValue, str)){
- request.setAttribute("errorMessage", "非法字符:" + str);
- RequestDispatcher requestDispatcher = request.getRequestDispatcher("/error.jsp");
- requestDispatcher.forward(request, response);
- return;
- }
- }
- }
- }
- super.doFilterInternal(request, response, filterChain);
- }
- }
接下来需要在web.xml中进行配置:
[html] view plain copy
- <filter>
- <filter-name>InvalidCharacterFilter</filter-name>
- <filter-class>com.yangcq.filter.InvalidCharacterFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>InvalidCharacterFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
如果我们不使用Spring的CharacterEncodingFilter类,可以自己来写。
[java] view plain copy
- import java.io.IOException;
- import java.util.Enumeration;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import org.apache.commons.lang.StringUtils;
- /**
- * SelfDefineInvalidCharacterFilter:过滤request请求中的非法字符,防止脚本攻击
- */
- public class SelfDefineInvalidCharacterFilter implements Filter{
- public void destroy() {
- }
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
- String parameterName = null;
- String parameterValue = null;
- // 获取请求的参数
- @SuppressWarnings("unchecked")
- Enumeration<String> allParameter = request.getParameterNames();
- while(allParameter.hasMoreElements()){
- parameterName = allParameter.nextElement();
- parameterValue = request.getParameter(parameterName);
- if(null != parameterValue){
- for(String str : invalidCharacter){
- if (StringUtils.containsIgnoreCase(parameterValue, str)){
- request.setAttribute("errorMessage", "非法字符:" + str);
- RequestDispatcher requestDispatcher = request.getRequestDispatcher("/error.jsp");
- requestDispatcher.forward(request, response);
- return;
- }
- }
- }
- }
- filterChain.doFilter(request, response); // 执行目标资源,放行
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- }
- // 需要过滤的非法字符
- private static String[] invalidCharacter = new String[]{
- "script","select","insert","document","window","function",
- "delete","update","prompt","alert","create","alter",
- "drop","iframe","link","where","replace","function","onabort",
- "onactivate","onafterprint","onafterupdate","onbeforeactivate",
- "onbeforecopy","onbeforecut","onbeforedeactivateonfocus",
- "onkeydown","onkeypress","onkeyup","onload",
- "expression","applet","layer","ilayeditfocus","onbeforepaste",
- "onbeforeprint","onbeforeunload","onbeforeupdate",
- "onblur","onbounce","oncellchange","oncontextmenu",
- "oncontrolselect","oncopy","oncut","ondataavailable",
- "ondatasetchanged","ondatasetcomplete","ondeactivate",
- "ondrag","ondrop","onerror","onfilterchange","onfinish","onhelp",
- "onlayoutcomplete","onlosecapture","onmouse","ote",
- "onpropertychange","onreadystatechange","onreset","onresize",
- "onresizeend","onresizestart","onrow","onscroll",
- "onselect","onstaronsubmit","onunload","IMgsrc","infarction"
- };
- }
接下来需要在web.xml中进行配置:
[html] view plain copy
- <filter>
- <filter-name>SelfDefineInvalidCharacterFilter</filter-name>
- <filter-class>com.yangcq.filter.SelfDefineInvalidCharacterFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>SelfDefineInvalidCharacterFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
五、Filter的生命周期
5.1、Filter的创建
Filter的创建和销毁由web服务器负责。 web应用程序启动时,web服务器将创建Filter的实例对象,并调用其init方法,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作,filter对象只会创建一次,init方法也只会执行一次。通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。
5.2、Filter的销毁
web容器调用destroy方法销毁Filter。destroy方法在Filter的生命周期中仅执行一次。在destroy方法中,可以释放过滤器使用的资源。
5.3、FilterConfig接口
用户在配置filter时,可以使用<init-param>为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过filterConfig对象的方法,就可获得:
String getFilterName():得到filter的名称。
String getInitParameter(String name): 返回在部署描述中指定名称的初始化参数的值。如果不存在返回null.
Enumeration getInitParameterNames():返回过滤器的所有初始化参数的名字的枚举集合。
public ServletContext getServletContext():返回Servlet上下文对象的引用。
示例:利用FilterConfig得到filter配置信息
[java] view plain copy
- package com.yangcq.filter;
- import java.io.IOException;
- import java.util.Enumeration;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class FilterTest implements Filter {
- /* 过滤器初始化
- * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
- */
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- System.out.println("----过滤器初始化----");
- /**
- * <filter>
- <filter-name>FilterTest</filter-name>
- <filter-class>com.yangcq.filter.FilterTest</filter-class>
- <!--配置FilterTest过滤器的初始化参数-->
- <init-param>
- <description>FilterTest</description>
- <param-name>name</param-name>
- <param-value>gacl</param-value>
- </init-param>
- <init-param>
- <description>配置FilterTest过滤器的初始化参数</description>
- <param-name>like</param-name>
- <param-value>java</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo02</filter-name>
- <!--“/*”表示拦截所有的请求 -->
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- */
- //得到过滤器的名字
- String filterName = filterConfig.getFilterName();
- //得到在web.xml文件中配置的初始化参数
- String initParam1 = filterConfig.getInitParameter("name");
- String initParam2 = filterConfig.getInitParameter("like");
- //返回过滤器的所有初始化参数的名字的枚举集合。
- Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
- System.out.println(filterName);
- System.out.println(initParam1);
- System.out.println(initParam2);
- while (initParameterNames.hasMoreElements()) {
- String paramName = (String) initParameterNames.nextElement();
- System.out.println(paramName);
- }
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- System.out.println("FilterDemo02执行前!!!");
- chain.doFilter(request, response); //让目标资源执行,放行
- System.out.println("FilterDemo02执行后!!!");
- }
- @Override
- public void destroy() {
- System.out.println("----过滤器销毁----");
- }
- }
六、Filter的部署时的一些参数的含义
Filter的部署分为两个步骤:
1、注册Filter
2、映射Filter
6.1、注册Filter
开发好Filter之后,需要在web.xml文件中进行注册,这样才能够被web服务器调用。在web.xml文件中注册Filter范例:
[html] view plain copy
- <filter>
- <description>过滤器名称</description>
- <filter-name>自定义的名字</filter-name>
- <filter-class>com.yangcq.filter.FilterTest</filter-class>
- <!--配置FilterTest过滤器的初始化参数-->
- <init-param>
- <description>配置过滤器的初始化参数</description>
- <param-name>name</param-name>
- <param-value>gacl</param-value>
- </init-param>
- <init-param>
- <description>配置FilterTest过滤器的初始化参数</description>
- <param-name>like</param-name>
- <param-value>java</param-value>
- </init-param>
- </filter>
<description>用于添加描述信息,该元素的内容可为空,<description>可以不配置。
<filter-name>用于为过滤器指定一个名字,该元素的内容不能为空。
<filter-class>元素用于指定过滤器的完整的限定类名。
<init-param>元素用于为过滤器指定初始化参数,它的子元素<param-name>指定参数的名字,<param-value>指定参数的值。在过滤器中,可以使用FilterConfig接口对象来访问初始化参数。如果过滤器不需要指定初始化参数,那么<init-param>元素可以不配置。
6.2、映射Filter
在web.xml文件中注册了Filter之后,还要在web.xml文件中映射Filter
<!--映射过滤器-->
<filter-mapping>
<filter-name>FilterTest</filter-name>
<!--“/*”表示拦截所有的请求 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>元素用于设置一个 Filter 所负责拦截的资源。一个Filter拦截的资源可通过两种方式来指定:Servlet 名称和资源访问的请求路径
<filter-name>子元素用于设置filter的注册名称。该值必须是在<filter>元素中声明过的过滤器的名字
<url-pattern>设置 filter 所拦截的请求路径(过滤器关联的URL样式)
<servlet-name>指定过滤器所拦截的Servlet名称。
<dispatcher>指定过滤器所拦截的资源被 Servlet 容器调用的方式,可以是REQUEST,INCLUDE,FORWARD和ERROR之一,默认REQUEST。用户可以设置多个<dispatcher> 子元素用来指定 Filter 对资源的多种调用方式进行拦截。如下:
<filter-mapping>
<filter-name>testFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<dispatcher> 子元素可以设置的值及其意义:
REQUEST:当用户直接访问页面时,Web容器将会调用过滤器。如果目标资源是通过RequestDispatcher的include()或forward()方法访问时,那么该过滤器就不会被调用。
INCLUDE:如果目标资源是通过RequestDispatcher的include()方法访问时,那么该过滤器将被调用。除此之外,该过滤器不会被调用。
FORWARD:如果目标资源是通过RequestDispatcher的forward()方法访问时,那么该过滤器将被调用,除此之外,该过滤器不会被调用。
ERROR:如果目标资源是通过声明式异常处理机制调用时,那么该过滤器将被调用。除此之外,过滤器不会被调用。