Servlet中的过滤器相当于守护后台资源的一道关卡,我们可以在过滤器中进行身份校验、权限认证、请求过滤等。
过滤器本身并不难,我们只需要知道他的定义方法、作用范围、执行顺序即可。
网上对于过滤器执行顺序的描述可能会让人产生误解。
图片来源于网络
客户端请求到达的时候,经过一次过滤器。
服务器处理完请求的时候,经过一次过滤器。
虽然经过两次过滤器,但不代表同样的代码执行了两次。
下面做了个简单的测试,看下执行结果就应该知道真正的执行流程了。
测试环境
tomcat9(servlet4.0)
jdk1.8
新版servlet可以通过注解注册servlet组件以及过滤器,无需再到web.xml下注册了。
测试过程
测试之间要先知道filterChain(过滤链)是干嘛的。
一个过滤器处理完后,会把request和response对象通过filterchain传递给下一个过滤器,如果没有下一个过滤器,则会直接开始执行业务代码,
单个过滤器
定义一个过滤器A
@WebFilter(value = "
public MainController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
运行结果
2020-12-01 10:46:50 A:拦截1 2020-12-01 10:46:55 A:拦截2
执行顺序:
filterChain之前的代码 ——>业务处理——>filterChain之后的代码。
多个过滤器
servlet的注解在多个过滤器的情况下,是按照过滤器的名称来排序的,例如A开头的过滤器,在B开头的后面。
A过滤器
@WebFilter(value = "
public MainController() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("/WEB-INF/pages/main.jsp").forward(request, response);
// response.sendRedirect("/WEB-INF/pages/main.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
执行结果:
2020-12-01 11:09:38 A:拦截1 http://localhost:8080/StudentManage/mainUrl 2020-12-01 11:09:38 B:拦截1 2020-12-01 11:09:43 B:拦截2 2020-12-01 11:09:43 A:拦截2 2020-12-01 11:09:44 A:拦截1 http://localhost:8080/StudentManage/css/bootstrap.css.map 2020-12-01 11:09:44 B:拦截1 2020-12-01 11:09:44 B:拦截2 2020-12-01 11:09:44 A:拦截2
转发(forward)的页面中需要请求静态资源,再次触发了过滤器。
以上就是Servlet Filter过滤器执行顺序的详细内容,更多关于Servlet Filter过滤器的资料请关注考高分网其它相关文章!



