Filter的基本使用
注解方式@WebFilter("/*")
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")//访问所有资源
// @WebFilter("/index.jso")//访问具体资源
// @WebFilter("/user/*")//访问同一路径
// @WebFilter("*.jsp")//访问后缀名
public class FilterDemo1 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("FilterDemo11111111111被执行了........");
//放行
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
web.xml方式
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>demo</filter-name>
<filter-class>cn.ptg.web.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>demo</filter-name>
<!--拦截路径-->
<url-pattern>/*</url-pattern>
<!--拦截方式-->
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
</web-app>
拦截方式
//多种拦截方式,浏览器直接请求时转发时都会被拦截
@WebFilter(value = "/*",dispatcherTypes ={ DispatcherType.REQUEST, DispatcherType.FORWARD})
//默认拦截,浏览器直接请求时会被拦截
@WebFilter(value = "/*",dispatcherTypes = DispatcherType.REQUEST)
//只有转发时才会被拦截
@WebFilter(value = "/*",dispatcherTypes = DispatcherType.FORWARD)
过滤器链
执行顺序
- 注解方式:根据字符串大小顺序执行,每个字符串比较值小的先执行
- web.xml:代码编辑的顺序执行