过滤器的创建和执行顺序
8.1.1创建并配置过滤器
P143 重点是如何创建并配置(xml)
1.创建
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
2.配置
- 注解方式:所有路径不能是多个*,可以配置多个过滤路径
- xml方式
3.注解方式
@WebFilter("/*")
@WebFilter(filterName = "myFilter",urlPatterns = {"/*"})
4.xml方式
<filter>
<filter-name>hellohello</filter-name>
<filter-class>demo.HelloServlet</filter-class>
</filter>
<filter-mapping>
<filter-name>hellohello</filter-name>
<url-pattern>/hellohello</url-pattern>
</filter-mapping>
<!-- 可以配置多个路径-->
<filter-mapping>
<filter-name>hellohello</filter-name>
<url-pattern>/hellohello2</url-pattern>
</filter-mapping>
5.基于xml的案例
public class HelloServlet 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("我是过滤器");
}
@Override
public void destroy() {
}
}
8.1.2 执行过滤器的详细过程
图1 Filter执行过程图2
8.1.3过滤器执行顺序
过滤器链的执行顺序
- 先在web.xml中查找过滤器执行
在web.xml中,则按照配置的<filter-mapping>顺序执行
- 再在注解的过滤中中选择执行:就是按照包名类名等的顺序执行
@WebFilter 按字母序执行