Filter细节过滤器拦截路径配置、Filter细节过滤器拦截方式配置、Filter细节过滤器链(多个过滤器)

Filter细节过滤器拦截路径配置

1.具体资源路径:/index.jsp 只有访问index.jsp资源时,过滤器才会被执行

2.拦截目录:/user/* 访问/user下的所有资源时,过滤器都会被执行

3.后缀名拦截:*.jsp 访问所有后缀名为jsp资源时,过滤器都会被执行

4.拦截所有资源:/* 访问所有资源时,过滤器都会被执行

//@WebFilter("/*")
//@WebFilter("/user/*")
//@WebFilter("*.jsp")
@WebFilter("/index.jsp")

Filter细节过滤器拦截方式配置

拦截方式配置:资源被访问的方式

  注解配置:

    设置dispatcherTypes属性

      1.REQUEST:默认值。浏览器直接请求资源

      2.FORWARD:转发访问资源

      3.INCLUDE:包含访问资源

      4.ERROR:错误跳转资源

      5.ASYNC:异步访问资源

  web.xml配置:

    在<filter-mapping>中加上这句即可

    <dispatcher>REQUEST</dispatcher>这里面的取值和注解的一样

注解配置

1.REQUEST:默认值。浏览器直接请求资源

复制代码
//浏览器直接请求资源时该过滤器会被执行
@WebFilter(value = "/index.jsp",dispatcherTypes = DispatcherType.REQUEST)
public class FilterD5 implements Filter {
    public void destroy() {}
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("FilterD5...");
        chain.doFilter(req, resp);
    }
    public void init(FilterConfig config) throws ServletException {}
}
复制代码
复制代码
@WebServlet("/user/ServletD1")
public class ServletD1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ServletD1");
        //转发到index.jsp
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
复制代码

使用Servlet转发访问

 

直接访问:

 

 

2.FORWARD:转发访问资源

@WebFilter(value = "/index.jsp",dispatcherTypes = DispatcherType.FORWARD)

直接访问

 

 

转发访问 

//浏览器直接请求资源时该过滤器会被执行或转发访问index.jsp都会被执行
@WebFilter(value = "/index.jsp",dispatcherTypes ={DispatcherType.FORWARD,DispatcherType.REQUEST})

Filter细节过滤器链(多个过滤器)

执行顺序:如果有两个过滤器:过滤器1和过滤器2

  1.过滤器1

  2.过滤器2  

  3.资源执行

  4.过滤器2

  5.过滤器1

过滤器先后执行问题:

  1.注解配置:按照类名的字符串比较规则比较,值小的先执行

    AFilter 和 BFilter :AFilter就先执行

  2.web.xml配置:<filter - mapping>谁定义在上边,谁先执行

 

posted @   魔光领域  阅读(736)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示