源码请见共享目录CSDN/JavaEE基础/1. SimpleFilter.zip
一、目标
书写过滤器,过滤指定的地址
二、说明
编写的过滤器,要实现javax.servlet.Filter接口!Filter接口的生命周期如下:
每个过滤器随着jvm的启动而初始化,jvm的关闭而关闭,在程序执行过程中负责拦截请求,用户可以定义规则判断是否调用chain.doFilter(request, response)去做相应servlet操作。
三、代码
- 增加servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
- 编写过滤器
public class MyFilter implements Filter{
public void destroy() {
System.out.println("destroy");
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain chain) throws IOException, ServletException {
System.out.println("doFilter");
chain.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
System.out.println("init");
}
}
- 编写servlet
public class Test extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("Hello,GET!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("Hello,POST!");
}
}
- 配置servlet和filter
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>Controller.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>Filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<!--拦截所有/test开始的url-->
<url-pattern>/test/*</url-pattern>
</filter-mapping>
</web-app>
四、总结
用户可以自定义多个Filter,每个Filter可以拦截1个或多个URL请求(分POST、GET等请求),这些Filter系统会链接在一起,形成FilterChain。
,方便访问某个URL时调用。