Java

Java过滤器(Filter)

2020-09-11  本文已影响0人  丿星纟彖彳亍

1、简介

Filter也称之为过滤器,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp、Servlet、静态图片文件或静态html文件等进行拦截,从而实现一些特殊或高级的功能。如:

过滤器Filter是在开发web应用时,实现了Servlet API中提供了的Java类Filter接口。

通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,示例:

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

2、 原理

Filter接口中有一个doFilter方法,当我们编写好Filter,并配置对哪个web资源进行拦截后,WEB服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可达到如下目的:

web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,若调用,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则不会被访问。

3、 开发流程

3.1 步骤

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中配置过滤器:

<?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.1 Filter链

在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。

web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。

在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。

4、生命周期

Filter的创建和销毁由web服务器负责。

4.3 FilterConfig接口

用户在配置filter时,可以使用<init-param>为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。因此开发人员在编写filter时,通过filterConfig对象的方法,就可获得:

public class FilterTest implements Filter {
    /* 过滤器初始化
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //得到过滤器的名字
        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() { //过滤器销毁
    }
}
           <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>

5、 Spring框架下,过滤器的配置

Spring框架中很多过滤器都不用自己来写了,Spring为我们写好了一些常用的过滤器。下面我们就以字符编码的过滤器CharacterEncodingFilter为例:

    <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这个过滤器的关键代码范例:

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

防止脚本攻击的过滤器(InvilidCharacterFilter):

/*
 * 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中的配置(部署时一些参数的含义):

    <filter>
        <filter-name>InvalidCharacterFilter</filter-name>//用于为过滤器指定一个名字,该元素的内容不能为空
        <filter-class>com.yangcq.filter.InvalidCharacterFilter</filter-class>//元素用于指定过滤器的完整的限定类名
    <!--配置FilterTest过滤器的初始化参数-->
    <init-param>//元素用于为过滤器指定初始化参数,在过滤器中,可以使用FilterConfig接口对象来访问初始化参数。如果过滤器不需要指定初始化参数,那么<init-param>元素可以不配置。
        <description>配置过滤器的初始化参数</description>
        <param-name>name</param-name>
        <param-value>gacl</param-value>
    </init-param>

    </filter>
    <filter-mapping>//元素用于设置一个 Filter 所负责拦截的资源。一个Filter拦截的资源可通过两种方式来指定:Servlet 名称和资源访问的请求路径
        <filter-name>InvalidCharacterFilter</filter-name>//子元素用于设置filter的注册名称。该值必须是在<filter>元素中声明过的过滤器的名字
        <url-pattern>/*</url-pattern>// “/*”表示拦截所有的请求, 设置 filter 所拦截的请求路径(过滤器关联的URL样式)
        <dispatcher>REQUEST</dispatcher>//指定过滤器所拦截的资源被 Servlet 容器调用的方式,可以是REQUEST,INCLUDE,FORWARD和ERROR之一,默认REQUEST。用户可以设置多个<dispatcher> 子元素用来指定 Filter 对资源的多种调用方式进行拦截
 // REQUEST:当用户直接访问页面时,Web容器将会调用过滤器。如果目标资源是通过RequestDispatcher的include()或forward()方法访问
时,那么该过滤器就不会被调用。
   // INCLUDE:如果目标资源是通过RequestDispatcher的include()方法访问时,那么该过滤器将被调用。除此之外,该过滤器不会被调用。
    // FORWARD:如果目标资源是通过RequestDispatcher的forward()方法访问时,那么该过滤器将被调用,除此之外,该过滤器不会被调用。
    // ERROR:如果目标资源是通过声明式异常处理机制调用时,那么该过滤器将被调用。除此之外,过滤器不会被调用。
    </filter-mapping>

若不使用Spring的CharacterEncodingFilter类,可以自己来写(web.xml配置类似,改个名):

/**
 * 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"
    };
}
上一篇下一篇

猜你喜欢

热点阅读