Filter简介
- Filter也称之为过滤器,它是Servlet技术中最激动人心的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
- Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,如下所示:
Filter是如何实现拦截的?
- Filter接口中有一个doFilter方法,当开发人员编写好Filter,并配置对哪个web资源进行拦截后,WEB服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法,因此,在该方法内编写代码可达到如下目的:
- 调用目标资源之前,让一段代码执行
- 是否调用目标资源(即是否让用户访问web资源)。
- web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则web资源不会被访问。
- 调用目标资源之后,让一段代码执行
【实例1】: Filter开发
添加过滤器
新建一个web项目,创建class类继承Filter接口
FilterDemo1.java
- package com.hbsi.filter;
- 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;
- public class FilterDemo1 implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- System.out.println("FilterDemo1");
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- 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_2_5.xsd">
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- This is my JSP page. <br>
- </body>
- </html>
请求被过滤器拦截,未执行jsp页面的输出内容,只是在控制台输出FilterDemo.java里的输出内容
如下图所示
控制台输出:
调用过滤链的方法显示被过滤内容
FilterDemo1.java
- package com.hbsi.filter;
- 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;
- public class FilterDemo1 implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- System.out.println("FilterDemo1");
- //找下一个过滤器,如果没有,让目标资源执行
- chain.doFilter(request, response);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
控制台输出:
【总结】配了过滤器,先走到过滤器,由过滤器拦截进行相应处理之后,通过过滤器链得doFilter方法往下传
如果有下一个过滤器传给下一个过滤器,如果没有,直接传给目标资源。
发回客户端,决定是否对response进行修改
FiterDemo1.java
- package com.hbsi.filter;
- 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;
- public class FilterDemo1 implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- System.out.println("FilterDemo1");
- //找下一个过滤器,如果没有,让目标资源执行
- chain.doFilter(request, response);
- System.out.println("FilterDemo1 after");
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <%System.out.println("index.jsp"); %>
- This is my JSP page. <br>
- </body>
- </html>
控制台输出:
【总结】
发出请求,通过FiterDemo1执行doFilter方法,之后相当于我的请求进行拦截了,先对请求进行处理,
先输出FiterDemo1,找目标资源执行,找到index.jsp,执行目标资源,response要返回去,输出FiterDemo1 after
Filter开发入门
Filter开发分为二个步骤:- 编写java类实现Filter接口,并实现其doFilter方法。
- 在 web.xml 文件中使用<filter>和<filter-mapping>元素对编写的filter类进行注册,并设置它所能拦截的资源。
- 在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。
- web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。
【实例】Filter链实验
第一个过滤器配在第二个过滤器前FilterChain.java
- package com.hbsi.filter;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class FilterChain implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- javax.servlet.FilterChain chain) throws IOException,
- ServletException {
- // TODO Auto-generated method stub
- System.out.println("22222222 before");
- chain.doFilter(request, response); //执行目标资源
- System.out.println("2222222 after");
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- 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_2_5.xsd">
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
控制台输出:
第二个过滤器配在第一个过滤器前
FilterChain.java
- package com.hbsi.filter;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class FilterChain implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- javax.servlet.FilterChain chain) throws IOException,
- ServletException {
- // TODO Auto-generated method stub
- System.out.println("22222222 before");
- chain.doFilter(request, response); //执行目标资源
- System.out.println("2222222 after");
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- 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_2_5.xsd">
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
控制台输出:
过滤器链只对同一种文件形式过滤
FilterChain.java
- package com.hbsi.filter;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class FilterChain implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- javax.servlet.FilterChain chain) throws IOException,
- ServletException {
- // TODO Auto-generated method stub
- System.out.println("22222222 before");
- chain.doFilter(request, response); //执行目标资源
- System.out.println("2222222 after");
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- 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_2_5.xsd">
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
控制台输出:
Servlet过滤器
- Filter不是一个Servlet,它不能产生一个response,它能够在一个request到达Servlet之前预处理request,也可以在离开Servlet时处理response。
- 将多个过滤器组成过滤器链,每个过滤器在应用程序中执行一个任务,这样有助于确保它们的模块性和复用性。
- 当Web容器收到一个请求时,将发生多个操作:
- Web容器对请求执行自己的预处理。在这一步中发生的事情由容器供应商负责。
- Web容器检查有没有与所请求的URL匹配的URL模式的过滤器。
- Web容器使用一个匹配的URL模式定位第一个过滤器。执行该过滤器的代码。
- 如果还有其他具有匹配URL模式的过滤器,则执行其代码,持续该过程,直到不再有其他具有匹配URL模式的过滤器。
- 如果没有发生错误,则将请求传递到目标Servlet。
- 该Servlet将应答传回其调用者。应用到请求上的最后一个过滤器将成功为应用到应答上的第一个过滤器。
- 最初应用到请求上的第一个过滤器将应答传递给Web容器。
- public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain);是Filter中最核心的方法。
- 参数FilterChain类型的对象是保存多个过滤器执行顺序的对象。
- 为什么叫过滤器链呢?一个Web容器中可以有多个过滤器,这些过滤器就像珠子被线串在了一起,调用它们的时候一个接一个进行调用。
- 过滤器的调用顺序怎么确定呢?调用过滤器的先后顺序按照在web.xml文件中声明的先后顺序。通过调用FilterChain对象的doFilter()方法,可以调用下一个过滤器的doFilter()方法,如果下一个过滤器是最后一个,则调用客户端请求的Servlet、JSP或其他文件。
Filter的生命周期
- init(FilterConfig filterConfig)throws ServletException:
- 和我们编写的Servlet程序一样,Filter的创建和销毁由WEB服务器负责。 web 应用程序启动时,web 服务器将创建Filter 的实例对象,并调用其init方法,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作(注:filter对象只会创建一次,init方法也只会执行一次。示例 )
- 开发人员通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。
- destroy():
- 在Web容器卸载 Filter 对象之前被调用。该方法在Filter的生命周期中仅执行一次。在这个方法中,可以释放过滤器使用的资源。
【实例】生命周期实例
FilterShengZhou.java
- package com.hbsi.filter;
- 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;
- public class FilterShengZhou implements Filter {
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- System.out.println("init");
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- 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_2_5.xsd">
- <!--
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- -->
- <filter>
- <filter-name>FilterShengZhou</filter-name>
- <filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterShengZhou</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
如图所示,web启动时进行初始化
在过滤器里配置初始化信息
FilterShengZhou.java
- package com.hbsi.filter;
- 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;
- public class FilterShengZhou implements Filter {
- private FilterConfig config = null;
- public void destroy() {
- // TODO Auto-generated method stub
- System.out.println("destroy");
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- //根据参数名字返回参数值
- System.out.println(config.getInitParameter("abc"));
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- this.config = filterConfig;
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- 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_2_5.xsd">
- <!--
- <filter>
- <filter-name>FilterChain</filter-name>
- <filter-class>com.hbsi.filter.FilterChain</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterChain</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.hbsi.filter.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>*.html</url-pattern>
- </filter-mapping>
- -->
- <filter>
- <filter-name>FilterShengZhou</filter-name>
- <filter-class>com.hbsi.filter.FilterShengZhou</filter-class>
- <init-param>
- <param-name>abc</param-name>
- <param-value>aaaaa</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>FilterShengZhou</filter-name>
- <url-pattern>*.jsp</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
调用destory方法
FilterShengZhou.java
- package com.hbsi.filter;
- 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;
- public class FilterShengZhou implements Filter {
- private FilterConfig config = null;
- public void destroy() {
- // TODO Auto-generated method stub
- System.out.println("destroy");
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- // TODO Auto-generated method stub
- //根据参数名字返回参数值
- System.out.println(config.getInitParameter("abc"));
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- this.config = filterConfig;
- }
- }
关闭Tomcat时候
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上下文对象的引用。