Filter过滤器
目录
Filter概述
Filter和Servlet及Listener称之为Servlet三大技术,Filter是一个过滤器,可以将请求或响应拦截,拦截中的请求或响应,可以对其中的内容进行操作。操作完成后,可以选择放行或不放行当前请求或响应。
Filter创建
创建一个类,只需要实现了Filter接口,即可成为一个过滤器。
package cn.zyj.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 FirstFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("过滤器销毁");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("过滤器运行");
arg2.doFilter(arg0, arg1);
System.out.println("after");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("过滤器创建");
}
}
<!--web.xml配置,/*表示拦截所有请求-->
<filter>
<filter-name>firstfilter</filter-name>
<filter-class>cn.zyj.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>firstfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filter方法实现
Method Summary | |
void | destroy() Called by the web container to indicate to a filter that it is being taken out of service. 在filter被移除web容器时,会自动调用destroy方法,完成善后的操作。移除web容器:删除web应用 。关闭tomcat |
void | doFilter(ServletRequest request, ServletResponse response, FilterChain chain) The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. 在过滤器拦截到请求之后,请求对应的响应,也会被过滤器拦截,请求响应只要被拦截都会经过这个dofilter方法。在这个方法中可以对请求响应中的数据,作出处理。处理完成之后,可以选择放行或不放行。 chain.doFilter(request,response); 如果放行,在放行代码的前后,还可以添加额外的操作。 |
void | init(FilterConfig filterConfig) Called by the web container to indicate to a filter that it is being placed into service. 在web容器启动时,filter被自动加载到web容器中,会自动调用init方法完成初始化的操作。 |
- 责任链模式
在过滤器中存在责任链模式。所谓责任链就是多个过滤器组成的链。如果有任何 一个过滤器没有放行,则这个请求无法到达对应的web资源。
当配置多个Filter过滤器时,它们存在一定的拦截顺序,这个拦截顺序由filter-mapping的配置顺序来决定。
- 过滤器的生命周期
当服务器启动时,filter会随着服务器的启动而加载,自动调用init方法完成初始化的操作,提供拦截请求与响应服务,在拦截到请求或响应后,会通过doFilter方法,在doFilter方法中,可以选择放行或不放行请求响应,如果放行,则在放行前后可以添加额外的操作。如果不放行,不能调用chain.doFilter(request,response);在服务器关闭的时候,filter也会随着服务器关闭而关闭,会自动调用destory方法进行善后。