一. Filter介绍
Filter主要是对一些WEB资源的拦截,如常用的路径拦截,也可对servlet,jsp等资源拦截,但是用得比较少。
执行流程:浏览器->Web服务器->Filter->Web资源
二.Filter生命周期
当服务器启动的时候会执行一次Filter的创建,然后执行一次Filter的初始化,注意,Filter只执行一次创建和一次初始化,当访问到Filter的时候,会执行doFilter方法,当服务器关闭时执行一次destory方法。
三.Filter用法
1.实现Filter
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
public class Filter implements javax.servlet.Filter {
public Filter() {
System.out.println("--------构造方法");
}
public void destroy() {
System.out.println("---------销毁");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("---------doFilter");
System.out.println("执行doFilter前");
chain.doFilter(request, response);
System.out.println("执行doFilter后");
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("---------init");
}
}
2.新建Servlet类
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FilterServlet extends GenericServlet {
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("执行服务");
}
}
3.web.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>WebFilter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>myFilter1</filter-name>
<filter-class>Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>FilterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/servlet.do</url-pattern>
</servlet-mapping>
</web-app>
通过上面的访问路径先执行Filter再执行Servlet,执行结果:
---------doFilter
执行doFilter前
执行doFilter后
注意:当doFilter方法中不执行
chain.doFilter(request, response);
方法时,将不会执行Servlet中service方法。