java 过滤器拦截请求_创建一个过滤器拦截所有请求

项目结构:

45ff6996d403b74706c09c0b79d6550c.png

AFilter:

packagecn.itcast.web.filter;

import javax.servlet.*;

importjava.io.IOException;

public class AFilter implementsFilter {

/**

* init方法在filter创建之后立即执行,用来做初始化

* @param filterConfig

* @throws ServletException

*/@Override

public void init(FilterConfig filterConfig) throwsServletException {

System.out.println("过滤器初始化!");

}

/**

* 每次过滤时都会执行

* @param servletRequest

* @param servletResponse

* @param filterChain

* @throws IOException

* @throws ServletException

*/@Override

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throwsIOException, ServletException {

System.out.println("过滤器拦截。。。");

filterChain.doFilter(servletRequest, servletResponse);

System.out.println("回来执行doFilter方法。。。");

}

/**

* destroy方法在销毁之前执行,用来对非内存资源释放

*/@Override

public voiddestroy() {

System.out.println("过滤器销毁!");

}

}

web.xml配置

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_3_1.xsd"

version="3.1">

AServlet

cn.itcast.web.servlet.AServlet

AServlet

/AServlet

AFilter

cn.itcast.web.filter.AFilter

AFilter

/*

index.jsp页面

Title

index.jsp页面

控制台输出:

项目启动时执行init方法

77a2c7522dc9efa99b1cc5e5ec20431b.png

执行doFilter方法

1a879e3b7715a0189b972de5d621236f.png

关闭服务器销毁filter

b191b8c8b54c1c3bd08e7320f94e6c90.png

销毁filter之前会调用destroy方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值