Java三大器之过滤器(Filter)的工作原理和代码演示

转自:http://blog.csdn.net/reggergdsg/article/details/52821502
一、Filter简介

  Filter也称之为过滤器,它是Servlet技术中最激动人心的技术之一,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp,
Servlet, 静态图片文件或静态html文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等
一些高级功能。
  Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。通过Filter
技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,Filter接口源代码:
  1. public abstract interface Filter{  
  2.     public abstract void init(FilterConfig paramFilterConfig) throws ServletException;  
  3.     public abstract void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain   
  4.         paramFilterChain) throws IOException, ServletException;  
  5.     public abstract void destroy();  
  6. }  
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类进行注册,并设置它所能拦截的资源。

过滤器范例:

  1. import java.io.IOException;  
  2. import javax.servlet.Filter;  
  3. import javax.servlet.FilterChain;  
  4. import javax.servlet.FilterConfig;  
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.ServletRequest;  
  7. import javax.servlet.ServletResponse;  
  8. /** 
  9.  * @author yangcq 
  10.  * @description 过滤器Filter的工作原理 
  11.  */  
  12. public class FilterTest implements Filter{  
  13.   
  14.     public void destroy() {  
  15.         System.out.println(”—-Filter销毁—-“);  
  16.     }  
  17.   
  18.     public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException {  
  19.         // 对request、response进行一些预处理  
  20.         request.setCharacterEncoding(”UTF-8”);  
  21.         response.setCharacterEncoding(”UTF-8”);  
  22.         response.setContentType(”text/html;charset=UTF-8”);  
  23.         System.out.println(”—-调用service之前执行一段代码—-“);  
  24.         filterChain.doFilter(request, response); // 执行目标资源,放行  
  25.         System.out.println(”—-调用service之后执行一段代码—-“);  
  26.     }  
  27.   
  28.     public void init(FilterConfig arg0) throws ServletException {  
  29.         System.out.println(”—-Filter初始化—-“);  
  30.     }  
  31. }  
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中配置过滤器:
  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <web-app version=“3.0”   
  3.     xmlns=“http://java.sun.com/xml/ns/javaee”   
  4.     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”   
  5.     xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”>  
  7.   <display-name></display-name>      
  8.   <welcome-file-list>  
  9.     <welcome-file>index.jsp</welcome-file>  
  10.   </welcome-file-list>  
  11.   <!–配置过滤器–>  
  12.   <filter>  
  13.       <filter-name>FilterTest</filter-name>  
  14.       <filter-class>com.yangcq.filter.FilterTest</filter-class>  
  15.   </filter>  
  16.   <!–映射过滤器–>  
  17.   <filter-mapping>  
  18.       <filter-name>FilterTest</filter-name>  
  19.       <!–“/*”表示拦截所有的请求 –>  
  20.       <url-pattern>/*</url-pattern>  
  21.   </filter-mapping>  
  22. </web-app>  
<?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框架下,如果配置过滤器。
  1. <filter>  
  2.     <filter-name>encodingFilter</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.     <init-param>  
  9.         <param-name>forceEncoding</param-name>  
  10.         <param-value>true</param-value>  
  11.     </init-param>  
  12. </filter>  
  13.   
  14. <filter-mapping>  
  15.     <filter-name>encodingFilter</filter-name>  
  16.     <url-pattern>/*</url-pattern>  
  17. </filter-mapping>  
    <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这个过滤器的关键代码,感受
一下,大师的风采,如果我们写过滤器的话,可以以此为范例。
  1. package org.springframework.web.filter;  
  2. import java.io.IOException;  
  3. import javax.servlet.FilterChain;  
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import org.springframework.util.ClassUtils;  
  8. public class CharacterEncodingFilter extends OncePerRequestFilter{  
  9.     private static final boolean responseSetCharacterEncodingAvailable = ClassUtils.hasMethod(  
  10.         class javax servlet http HttpServletResponse, “setCharacterEncoding”new Class[] { String.class });  
  11.     // 需要设置的编码方式,为了支持可配置,Spring把编码方式设置成了一个变量  
  12.     private String encoding;  
  13.     // 是否强制使用统一编码,也是为了支持可配置  
  14.     private boolean forceEncoding;  
  15.     // 构造器,在这里,Spring把forceEncoding的值默认设置成了false  
  16.     public CharacterEncodingFilter(){  
  17.         this.forceEncoding = false;  
  18.     }  
  19.     // encoding/forceEncoding的setter方法  
  20.     public void setEncoding(String encoding){  
  21.         this.encoding = encoding;  
  22.     }  
  23.     public void setForceEncoding(boolean forceEncoding){  
  24.         this.forceEncoding = forceEncoding;  
  25.     }  
  26.     // Spring通过GenericFilterBean抽象类,对Filter接口进行了整合,  
  27.     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)  
  28.         throws ServletException, IOException{  
  29.         if ((this.encoding != null) && (((this.forceEncoding) || (request.getCharacterEncoding() == null)))) {  
  30.             request.setCharacterEncoding(this.encoding);  
  31.             if ((this.forceEncoding) && (responseSetCharacterEncodingAvailable)) {  
  32.                 response.setCharacterEncoding(this.encoding);  
  33.             }  
  34.         }  
  35.         filterChain.doFilter(request, response);  
  36.     }  
  37. }  
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(防止脚本攻击的过滤器)

  1. import java.io.IOException;  
  2. import java.util.Enumeration;  
  3. import javax.servlet.FilterChain;  
  4. import javax.servlet.RequestDispatcher;  
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8. import org.apache.commons.lang.StringUtils;  
  9. import org.springframework.web.filter.CharacterEncodingFilter;  
  10. /* 
  11.  * InvalidCharacterFilter:过滤request请求中的非法字符,防止脚本攻击 
  12.  * InvalidCharacterFilter继承了Spring框架的CharacterEncodingFilter过滤器,当然,我们也可以自己实现这样一个过滤器 
  13.  */  
  14. public class InvalidCharacterFilter extends CharacterEncodingFilter{  
  15.     // 需要过滤的非法字符  
  16.     private static String[] invalidCharacter = new String[]{  
  17.         ”script”,“select”,“insert”,“document”,“window”,“function”,  
  18.         ”delete”,“update”,“prompt”,“alert”,“create”,“alter”,  
  19.         ”drop”,“iframe”,“link”,“where”,“replace”,“function”,“onabort”,  
  20.         ”onactivate”,“onafterprint”,“onafterupdate”,“onbeforeactivate”,  
  21.         ”onbeforecopy”,“onbeforecut”,“onbeforedeactivateonfocus”,  
  22.         ”onkeydown”,“onkeypress”,“onkeyup”,“onload”,  
  23.         ”expression”,“applet”,“layer”,“ilayeditfocus”,“onbeforepaste”,  
  24.         ”onbeforeprint”,“onbeforeunload”,“onbeforeupdate”,  
  25.         ”onblur”,“onbounce”,“oncellchange”,“oncontextmenu”,  
  26.         ”oncontrolselect”,“oncopy”,“oncut”,“ondataavailable”,  
  27.         ”ondatasetchanged”,“ondatasetcomplete”,“ondeactivate”,  
  28.         ”ondrag”,“ondrop”,“onerror”,“onfilterchange”,“onfinish”,“onhelp”,  
  29.         ”onlayoutcomplete”,“onlosecapture”,“onmouse”,“ote”,  
  30.         ”onpropertychange”,“onreadystatechange”,“onreset”,“onresize”,  
  31.         ”onresizeend”,“onresizestart”,“onrow”,“onscroll”,  
  32.         ”onselect”,“onstaronsubmit”,“onunload”,“IMgsrc”,“infarction”  
  33.     };  
  34.   
  35.     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)  
  36.             throws ServletException, IOException{     
  37.         String parameterName = null;  
  38.         String parameterValue = null;  
  39.         // 获取请求的参数  
  40.         @SuppressWarnings(“unchecked”)  
  41.         Enumeration<String> allParameter = request.getParameterNames();  
  42.         while(allParameter.hasMoreElements()){  
  43.             parameterName = allParameter.nextElement();  
  44.             parameterValue = request.getParameter(parameterName);  
  45.             if(null != parameterValue){  
  46.                 for(String str : invalidCharacter){  
  47.                     if (StringUtils.containsIgnoreCase(parameterValue, str)){  
  48.                         request.setAttribute(”errorMessage”“非法字符:” + str);  
  49.                         RequestDispatcher requestDispatcher = request.getRequestDispatcher(”/error.jsp”);  
  50.                         requestDispatcher.forward(request, response);  
  51.                         return;  
  52.                     }  
  53.                 }  
  54.             }  
  55.         }  
  56.         super.doFilterInternal(request, response, filterChain);  
  57.     }  
  58. }  
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中进行配置:
  1. <filter>  
  2.     <filter-name>InvalidCharacterFilter</filter-name>  
  3.     <filter-class>com.yangcq.filter.InvalidCharacterFilter</filter-class>  
  4. </filter>  
  5. <filter-mapping>  
  6.     <filter-name>InvalidCharacterFilter</filter-name>  
  7.     <url-pattern>/*</url-pattern>  
  8. </filter-mapping>  
    <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类,可以自己来写。
  1. import java.io.IOException;  
  2. import java.util.Enumeration;  
  3. import javax.servlet.Filter;  
  4. import javax.servlet.FilterChain;  
  5. import javax.servlet.FilterConfig;  
  6. import javax.servlet.RequestDispatcher;  
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.ServletRequest;  
  9. import javax.servlet.ServletResponse;  
  10. import org.apache.commons.lang.StringUtils;  
  11. /** 
  12.  * SelfDefineInvalidCharacterFilter:过滤request请求中的非法字符,防止脚本攻击 
  13.  */  
  14. public class SelfDefineInvalidCharacterFilter implements Filter{  
  15.   
  16.     public void destroy() {  
  17.           
  18.     }  
  19.   
  20.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {  
  21.         String parameterName = null;  
  22.         String parameterValue = null;  
  23.         // 获取请求的参数  
  24.         @SuppressWarnings(“unchecked”)  
  25.         Enumeration<String> allParameter = request.getParameterNames();  
  26.         while(allParameter.hasMoreElements()){  
  27.             parameterName = allParameter.nextElement();  
  28.             parameterValue = request.getParameter(parameterName);  
  29.             if(null != parameterValue){  
  30.                 for(String str : invalidCharacter){  
  31.                     if (StringUtils.containsIgnoreCase(parameterValue, str)){  
  32.                         request.setAttribute(”errorMessage”“非法字符:” + str);  
  33.                         RequestDispatcher requestDispatcher = request.getRequestDispatcher(”/error.jsp”);  
  34.                         requestDispatcher.forward(request, response);  
  35.                         return;  
  36.                     }  
  37.                 }  
  38.             }  
  39.         }  
  40.         filterChain.doFilter(request, response); // 执行目标资源,放行  
  41.     }  
  42.   
  43.     public void init(FilterConfig filterConfig) throws ServletException {  
  44.           
  45.     }  
  46.     // 需要过滤的非法字符  
  47.     private static String[] invalidCharacter = new String[]{  
  48.         ”script”,“select”,“insert”,“document”,“window”,“function”,  
  49.         ”delete”,“update”,“prompt”,“alert”,“create”,“alter”,  
  50.         ”drop”,“iframe”,“link”,“where”,“replace”,“function”,“onabort”,  
  51.         ”onactivate”,“onafterprint”,“onafterupdate”,“onbeforeactivate”,  
  52.         ”onbeforecopy”,“onbeforecut”,“onbeforedeactivateonfocus”,  
  53.         ”onkeydown”,“onkeypress”,“onkeyup”,“onload”,  
  54.         ”expression”,“applet”,“layer”,“ilayeditfocus”,“onbeforepaste”,  
  55.         ”onbeforeprint”,“onbeforeunload”,“onbeforeupdate”,  
  56.         ”onblur”,“onbounce”,“oncellchange”,“oncontextmenu”,  
  57.         ”oncontrolselect”,“oncopy”,“oncut”,“ondataavailable”,  
  58.         ”ondatasetchanged”,“ondatasetcomplete”,“ondeactivate”,  
  59.         ”ondrag”,“ondrop”,“onerror”,“onfilterchange”,“onfinish”,“onhelp”,  
  60.         ”onlayoutcomplete”,“onlosecapture”,“onmouse”,“ote”,  
  61.         ”onpropertychange”,“onreadystatechange”,“onreset”,“onresize”,  
  62.         ”onresizeend”,“onresizestart”,“onrow”,“onscroll”,  
  63.         ”onselect”,“onstaronsubmit”,“onunload”,“IMgsrc”,“infarction”  
  64.     };  
  65.   
  66. }  
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中进行配置:
  1. <filter>  
  2.     <filter-name>SelfDefineInvalidCharacterFilter</filter-name>  
  3.     <filter-class>com.yangcq.filter.SelfDefineInvalidCharacterFilter</filter-class>  
  4. </filter>  
  5. <filter-mapping>  
  6.     <filter-name>SelfDefineInvalidCharacterFilter</filter-name>  
  7.     <url-pattern>/*</url-pattern>  
  8. </filter-mapping>  
    <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配置信息
  1. package com.yangcq.filter;  
  2. import java.io.IOException;  
  3. import java.util.Enumeration;  
  4. import javax.servlet.Filter;  
  5. import javax.servlet.FilterChain;  
  6. import javax.servlet.FilterConfig;  
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.ServletRequest;  
  9. import javax.servlet.ServletResponse;  
  10. public class FilterTest implements Filter {  
  11.   
  12.     /* 过滤器初始化 
  13.      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) 
  14.      */  
  15.     @Override  
  16.     public void init(FilterConfig filterConfig) throws ServletException {  
  17.         System.out.println(”—-过滤器初始化—-“);  
  18.         /** 
  19.          *  <filter> 
  20.                   <filter-name>FilterTest</filter-name> 
  21.                   <filter-class>com.yangcq.filter.FilterTest</filter-class> 
  22.                   <!–配置FilterTest过滤器的初始化参数–> 
  23.                   <init-param> 
  24.                       <description>FilterTest</description> 
  25.                       <param-name>name</param-name> 
  26.                       <param-value>gacl</param-value> 
  27.                   </init-param> 
  28.                   <init-param> 
  29.                       <description>配置FilterTest过滤器的初始化参数</description> 
  30.                       <param-name>like</param-name> 
  31.                       <param-value>java</param-value> 
  32.                   </init-param> 
  33.             </filter> 
  34.              
  35.              <filter-mapping> 
  36.                   <filter-name>FilterDemo02</filter-name> 
  37.                   <!–“/*”表示拦截所有的请求 –> 
  38.                   <url-pattern>/*</url-pattern> 
  39.              </filter-mapping> 
  40.          */  
  41.         //得到过滤器的名字  
  42.         String filterName = filterConfig.getFilterName();  
  43.         //得到在web.xml文件中配置的初始化参数  
  44.         String initParam1 = filterConfig.getInitParameter(”name”);  
  45.         String initParam2 = filterConfig.getInitParameter(”like”);  
  46.         //返回过滤器的所有初始化参数的名字的枚举集合。  
  47.         Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();  
  48.           
  49.         System.out.println(filterName);  
  50.         System.out.println(initParam1);  
  51.         System.out.println(initParam2);  
  52.         while (initParameterNames.hasMoreElements()) {  
  53.             String paramName = (String) initParameterNames.nextElement();  
  54.             System.out.println(paramName);  
  55.         }  
  56.     }  
  57.   
  58.     @Override  
  59.     public void doFilter(ServletRequest request, ServletResponse response,  
  60.             FilterChain chain) throws IOException, ServletException {  
  61.         System.out.println(”FilterDemo02执行前!!!”);  
  62.         chain.doFilter(request, response);  //让目标资源执行,放行  
  63.         System.out.println(”FilterDemo02执行后!!!”);  
  64.     }  
  65.   
  66.     @Override  
  67.     public void destroy() {  
  68.         System.out.println(”—-过滤器销毁—-“);  
  69.     }  
  70. }  
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范例:
  1. <filter>  
  2.     <description>过滤器名称</description>  
  3.     <filter-name>自定义的名字</filter-name>  
  4.     <filter-class>com.yangcq.filter.FilterTest</filter-class>  
  5.     <!–配置FilterTest过滤器的初始化参数–>  
  6.     <init-param>  
  7.         <description>配置过滤器的初始化参数</description>  
  8.         <param-name>name</param-name>  
  9.         <param-value>gacl</param-value>  
  10.     </init-param>  
  11.     <init-param>  
  12.         <description>配置FilterTest过滤器的初始化参数</description>  
  13.         <param-name>like</param-name>  
  14.         <param-value>java</param-value>  
  15.     </init-param>  
  16. </filter>  
<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:如果目标资源是通过声明式异常处理机制调用时,那么该过滤器将被调用。除此之外,过滤器不会被调用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值