我的网络应用中有2个过滤器和一个servlet。我使用@WebFilter注释以编程方式注册了过滤器。它们具有相同的URL模式。现在第一个过滤器调用FilterChain.doFilter,第二个过滤器调用RequestDispatcher.forward方法将请求转发给servlet。代码运行正常,因为第一个过滤器调用第二个过滤器,第二个过滤器调用servlet。我想知道,web.xml中没有过滤器条目,容器正在以正确的顺序调用它们。所以它只是一个巧合,或者我们可以在基于注释的配置中进行排序?
请找到以下代码。
第一次过滤:
@WebFilter(urlPatterns={"/*"},displayName="FirstFilterInFilterChain")
public class FirstFilterInFilterChain implements Filter{
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("Calling the Second Filter");
chain.doFilter(req, res);
System.out.println("Returning from Filter 1");
}
@Override
public void destroy() {
System.out.println("Inside Destroy method of Filter no 1");
}
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("Inside Init method of Filter no 1");
}
}
第二次过滤:
@WebFilter("/*")
public class SecondFilterInFilterChain implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/PostFilterServlet");
dispatcher.forward(request, response);
System.out.println("Returning from Filter 2");
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("Inside Init method of Filter no 2");
}
}
Servlet代码:
@WebServlet("/PostFilterServlet")
public class PostFilterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside PostFilterServlet");
}
}
控制台输出:
调用第二个过滤器
调用servlet
Inside PostFilterServlet
从过滤器2返回
从过滤器1返回