Init()
该方法是过滤器的初始化方法,Web容器创建过滤器后将调用这个方法,这个方法将调用web.xml中过滤器的参数。
doFilter()
这个方法完成实际的过滤操作。这里是过滤器的核心方法,当用户请求访问过滤器关联的URL时,web容器将调用过滤器的doFilter()方法。FilterChain参数可以调用chain.dofilter方法,将请求传给下一个过滤器(或者目标资源),或利用转发,重定向将请求转发到其他资源。
destory() web容器在销毁过滤器实例前调用该方法,在这个方法中可释放过滤器占用的资源(大多情况用不到)。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ImoocFilter</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<!-- filter的名字 -->
<filter-name>FirstFilter</filter-name>
<!-- filter的类名称 -->
<filter-class>com.imooc.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<!-- filter的名字 -->
<filter-name>FirstFilter</filter-name>
<!-- 用户请求的URL -->
<url-pattern>/*</url-pattern>
<!-- 过滤什么样的请求 -->
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
chain.doFilter的作用是将请求转发给过滤器链上的下一个对象