init() //启动服务器时执行
doFilter(ServletRequest ,ServletResponse , FilterChain)//当可以拦截的请求到达时,新建一个线程去执行。同Servlet一样,
destory()//关闭服务器时执行
public class FilterDemo1 implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//拦截时执行语句
//执行这一句,说明放行(让下一个过滤器执行,如果没有过滤器了,就执行执行目标资源)
chain.doFilter(req, resp);
//从后一个过滤器返回,或从目标资源返回时,执行语句。
}
public void init(FilterConfig config) throws ServletException {
}
}
实现方式一、在web.xml中配置
//filter用于注册过滤器
<filter>
<filter-name>FilterDemo1</filter-name>
<filter-class>FilterDemo1</filter-class>
<init-param>
<param-name>word_file</param-name>
<param-value>/WEB-INF/word.txt</param-value>
</init-param>
</filter>
//<filter-mapping>元素用于设置一个Filter 所负责拦截的资源
//一个Filter拦截的资源可通过两种方式来指定:Servlet 名称和资源访问的请求路径
<filter-mapping>
<filter-name>FilterDemo1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
实现方式二、在Filter类上直接写注解
@WebFilter(filterName = "FilterDemo1",urlPatterns = "/*")
权限验证(登录权限、资源访问权限...)
https://www.cnblogs.com/ygj09...
https://mp.weixin.qq.com/s?__... (Java3y)
Filter高级应用
https://mp.weixin.qq.com/s?__...