JavaWeb-三大器之过滤器

2020-01-08  本文已影响0人  Tian_Peng

概述

Filter也称之为过滤器,它是Servlet技术中最激动人心的技术之一。
WEB开发人员通过Filter技术,对web服务器管理的所有web资源。
例如:

Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。
通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截。
Filter接口源代码:

package javax.servlet;

import java.io.IOException;

public interface Filter {
    default void init(FilterConfig filterConfig) throws ServletException {
    }

    void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException;

    default void destroy() {
    }
}

Filter的工作原理

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

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

Filter开发流程

例如:

package com.tp.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * FileName: CharacterEncodingFilter
 * Author:   TP
 * Description:全局乱码处理过滤器
 */
public class CharacterEncodingFilter implements Filter {

    private FilterConfig filterConfig = null;
    //设置默认的字符编码
    private String defaultCharset = "UTF-8";

    public void init(FilterConfig filterConfig) throws ServletException {
        //得到过滤器的初始化配置信息
        System.out.println("字符过滤器初始化");
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String charset = filterConfig.getInitParameter("charset");
        if(charset==null){
            charset = defaultCharset;
        }
        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);
        response.setContentType("text/html;charset="+charset);
        System.out.println("----调用service之前执行一段代码----");
        chain.doFilter(request, response);
        System.out.println("----调用service之后执行一段代码----");
    }

    public void destroy() {
        System.out.println("字符过滤器被销毁");
    }
}

在web. xml中配置过滤器:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--全局解决中文乱码-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.tp.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>charset</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

启动项目,访问http://localhost:8080/,观察控制台输出:

停止项目,观察控制台输出:

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框架下,如果配置过滤器:

<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如下:

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;

public class CharacterEncodingFilter extends OncePerRequestFilter {
    private String encoding;
    private boolean forceEncoding = false;

    public CharacterEncodingFilter() {
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public void setForceEncoding(boolean forceEncoding) {
        this.forceEncoding = forceEncoding;
    }

    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) {
                response.setCharacterEncoding(this.encoding);
            }
        }

        filterChain.doFilter(request, response);
    }
}

又例如防止脚本攻击的过滤器:

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中进行配置:

<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>  

Filter的生命周期

FilterConfig接口

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

示例:利用FilterConfig得到filter配置信息

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的部署分为两个步骤:

注册Filter

开发好Filter之后,需要在web.xml文件中进行注册,这样才能够被web服务器调用。
在web.xml文件中注册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>  

其中:

映射Filter

在web.xml文件中注册了Filter之后,还要在web.xml文件中映射Filter:

<!--映射过滤器-->
  <filter-mapping>
      <filter-name>FilterTest</filter-name>
      <!--“/*”表示拦截所有的请求 -->
      <url-pattern>/*</url-pattern>
  </filter-mapping>

其中:

<filter-mapping>
    <filter-name>testFilter</filter-name>
    <url-pattern>/index.jsp</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

<dispatcher> 子元素可以设置的值及其意义:

上一篇下一篇

猜你喜欢

热点阅读