带有Servlet和Filter的嵌入式 Tomcat 的简单实例:
Tomcat tomcat = new Tomcat();
Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
FilterDef filterDefinition = new FilterDef();
filterDefinition.setFilterName(URLFilter.class.getSimpleName());
filterDefinition.setFilterClass(URLFilter.class.getName());
rootCtx.addFilterDef(filterDefinition);
FilterMap filter1mapping = new FilterMap();
filter1mapping.setFilterName(URLFilter.class.getSimpleName());
filter1mapping.addURLPattern("/*");
rootCtx.addFilterMap(filter1mapping);
Tomcat.addServlet(rootCtx, "Servlet1", new Servlet1());
rootCtx.addServletMapping("/Servlet1", "Servlet1");
URL过滤器实现:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
Boolean filtered = false;
System.out.println("request intercepted");
if (request.getAttribute("filtered") != null) {
filtered = true;
request.setAttribute("filtered", filtered);
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect("/Servlet1");
return;
} else {
filterChain.doFilter(request, response);
}
}
由于某种原因,这最终陷入了无限循环,并且永远不会到达 Servlet1。实现 URL 过滤器的正确方法是什么,以便我可以在传递响应之前仔细检查请求周围的参数?