- 问题引入
以往的Servlet中,有冗余代码,多个servlet都要进行编写
- 概念
过滤器(Filter)是处于客户端于服务器资源之间的一道技术。
图示:
- 过滤器的作用
- 执行地位在Servlet之前,客户端发送请求时,会先经过Filter,在到达目标Servlet。响应时,会根据执行流程再次反向执行Filter
- 可以解决多个Servlet共性代码的冗余问题
- 编写过滤器
Servlet API中提供了一个Filter接口,只要实现这个接口即可,实现这个接口的类就时过滤器
- 实现过程
- 编写java类实现Filter接口
- 在doFilter方法中编写拦截逻辑
- 设置拦截路径
@WebFilter(value = "/xxx")//拦截路径
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("拦截逻辑 Throwanexception");
//让请求继续
filterChain.doFilter( servletRequest,servletResponse );//让请求往下传递
}
@Override
public void destroy() {
}
}
过滤器配置的两种方式
- 注解配置
在自定义的Filter类上使用注解@WebFilter(value="/过滤目标资源")
- xml配置
在web.xml中配置
<filter>
<!-- 名称-->
<filter-name>ThrowanexceptionS</filter-name>
<!-- 过滤类全称-->
<filter-class>S.M.fileter.MyFilter</filter-class>
</filter>
<!-- 映射路径配置-->
<filter-mapping>
<!-- 名称-->
<filter-name>ThrowanexceptionS</filter-name>
<!-- 过滤器的url匹配规则和Servlet类-->
<url-pattern>/*</url-pattern>
</filter-mapping>
- 过滤器链
客户端向服务器请求后,服务器调用Servlet之前回执行一组过滤器,这组过滤器就叫做过滤器链
每一个过滤器实现某个特定的功能,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给此方法,在doFilter方法中,如果调用FilterChain对象中的doFilter方法,web服务器会检查FilterChain对象中是否还有filter。有调用第二个Filter,没有调用目标资源
- 过滤器优先级
Web应用中,可以有多个Filter,这些Filter组合起来就是Filter链
优先级:
- 如果是注解的话,按照类全名称的字符串顺序决定作用顺序
- 是web.xml,按照filter.mapping注册顺序,从上往下
- web.xml配置高于注解配置
- 注解和web.xml同时配置,会创建多个过滤器对象,造成过滤多次的现象
- 配置拦截路径的三种方式
- 精确拦截:如:/index.jsp /myservlet
- 后缀拦截:*.jsp、*.html、*.jpg
- 通配符拦截/*:表示拦截所有