Filter过滤器
Filter过滤器:它是JavaWeb的三大组件之一,它的的作用是,拦截请求,过滤响应。
拦截请求常见场景:
- 权限检查
- 日记操作
- 事务管理
Filter的实现
Filter过滤器的使用步骤
- 实现Filter接口
- 实现过滤方法doFilter()
- 到web.xml中配置Fliter的拦截路径
代码实现
public class MyFilter implements Filter {
//doFilter方法专门用于拦截请求,可以做权限检查
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//业务代码
//让程序继续访问用户的目标资源
filterChain.doFilter(servletRequest,servletResponse);
}
}
配置文件
<!--filter标签用于配置一个filter过滤器 -->
<filter>
<!-- 给filter过滤器起别名 -->
<filter-name>MyFilter</filter-name>
<!-- 配置filter的全类名 -->
<filter-class>com.gz.load.MyFilter</filter-class>
</filter>
<!--配置Filter过滤器的拦截路径 -->
<filter-mapping>
<!-- 当前拦截路径给那个filter使用-->
<filter-name>MyFilter</filter-name>
<!--配置拦截路径 -->
<url-pattern>/</url-pattern>
</filter-mapping>
Filter的生命周期
- 构造方法
- init初始化
- doFilter过滤方法
- destroy销毁
注意:前两步在web工程启动是已经执行,第三步每次拦截到请求就会执行
。第四步,web停止时执行。
FilterChain 过滤器链
FilterChain过滤器链,多个过滤器如何在一起工作。
Filter的拦截路径
精确匹配:
<url-pattern>/target.jsp</url-pattern>
表示请求的地址必须为:http://ip:port/工程路径/tatget.jsp
目录匹配:
<url-pattern>/admin/*</url-pattern>
表示请求的地址必须为:http://ip:port/工程路径/amdin/*
后缀名匹配
<url-pattern>*.action</url-pattern>
表示请求地址必须以.html 结尾才会拦截到