来自过滤器的java转发请求
我需要从http转发我的请求(到jsp,但我认为这无关紧要)。滤器 如果原始请求的URI通过了一些验证,我的过滤器就会运行
我找到了这个page that faced similar task
但我仍然需要考虑以下几点:
如何在
doFilter()
方法中获取ServletContext(以便调用前向API)getServletContext()
未被识别我必须在前锋之前
call chain.doFilter()
,在前锋之后还是根本不需要? 此外,如果我的验证通过了,还是只有在验证失败时(因为在这种情况下,我不会继续转发我的页面),我才需要调用chain.doFilter()
这个问题实际上继续this thread, 更明显的是,代码可以是这样的:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = ((HttpServletRequest)request);
String requestURI = httpServletRequest.getRequestURI();
String contextPath = httpServletRequest.getContextPath();
if (<this is my implementation of the validation of this filter>){
getServletContext().getRequestDispatcher(
"MySpecific.jsp").forward(request,response);
}
}
chain.doFilter(request,response);
}
# 1 楼答案
我想说的是,如果你转发了请求,你不应该调用
chain.doFilter()
——转发的请求将根据其自身的过滤器配置进行过滤。但是,如果验证失败,这取决于web应用程序的语义——如果原始页面是某种常见的错误/登录/欢迎屏幕,那么在验证失败时,您可能希望继续执行该操作。如果不了解更多的上下文,很难说