814~815 Filter过滤器拦截 路径,方式 的配置
4.过滤器配置详解
拦截路径配置:
1.具体资源路径:/index.jsp 只有访问index.jsp资源时,过滤器才会被执行
2.拦截目录: /user/* 访问/user下的所有资源时,过滤器都会被执行
3.后缀名拦截: *.jsp 访问所有后缀名为jsp资源时,过滤器都会被执行
4. 拦截所有资源:/* 访问所有资源时,过滤器都会被执行
//@WebFilter("/index.jsp")//具体资源路径: /index.jsp 只有访问index.jsp资源时,过滤器才会被执行
//@WebFilter("/user/*")//2.拦截目录: /user/* 访问/user下的所有资源时,过滤器都会被执行
//@WebFilter("")//3.后缀名拦截: *.jsp 访问所有后缀名为jsp资源时,过滤器都会被执行
//@WebFilter("/*")//4. 拦截所有资源:/* 访问所有资源时,过滤器都会被执行
public class FilterDemo4 implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
System.out.println("FilterDemo4...");
chain.doFilter(request, response);
}
}
拦截方式配置:资源被访问的方式
注解配置:
设置dispatcherTypes属性
1. REQUEST:默认值。浏览器直接请求资源
2. FORWARD:转发访问资源
3. INCLUDE:包含访问资源
4. ERROR:错误跳转资源
5. ASYNC:异步访问资源
web.xml配置
设置<dispatcher></dispatcher>标签即可
//浏览器直接请求index.jsp资源时,该过滤器会被执行
//@WebFilter(value="/index.jsp",dispatcherTypes = DispatcherType.REQUEST)
//只有转发访问index.jsp时,该过滤器才会被执行
//@WebFilter(value="/index.jsp",dispatcherTypes = DispatcherType.FORWARD)
//浏览器直接请求index.jsp或者转发访问index.jsp。该过滤器才会被执行
//@WebFilter(value="/*",dispatcherTypes ={ DispatcherType.FORWARD,DispatcherType.REQUEST})
public class FilterDemo5 implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("filterDemo5....");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
}

浙公网安备 33010602011771号