来自过滤器的转发请求

Spi*_*man 14 java filter java-ee

我需要转发我的要求(到JSP,但我不认为这是事)从http.Filter如果原请求的URI通过一些验证,我的过滤器运行.

我发现这个页面面临着类似的任务

我仍需要计算以下内容:

  1. 如何在doFilter()方法中获取ServletContext (为了调用前向API) getServletContext()不会重新签名

  2. 我是否必须call chain.doFilter()在前锋之前,之后还是没有前进?另外,chain.doFilter() 如果我的验证通过,或者只有在它失败的情况下我必须打电话(因为在这种情况下我不会继续转发我的页面)?

这个问题实际上继续这个线程,更明显的是,代码可能是这样的:

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);

    }
Run Code Online (Sandbox Code Playgroud)

Pét*_*rök 11

如何在doFilter()方法中获取ServletContext?

httpServletRequest.getSession().getServletContext();
Run Code Online (Sandbox Code Playgroud)

我是否必须在前锋之前调用chain.doFilter(),之后还是根本不调用?另外,如果我的验证通过,或者仅当它失败时,我必须调用chain.doFilter()(因为在这种情况下我不会继续转发我的页面)?

我会说,如果您转发了请求,则不应该调用chain.doFilter()- 转发的请求将根据其自己的过滤器配置进行过滤.如果验证失败,则取决于您的Web应用程序的语义是什么 - 如果原始页面是某种常规错误/登录/欢迎屏幕,您可能希望在验证失败时继续执行此操作.如果不了解更多背景,很难说.


小智 11

要获得 ServletContext,您有两个选择:

  • FilterConfig在初始化和调用期间存储关闭FilterConfig.getServletContext()

  • 呼叫 HttpServletRequest.getSession().getServletContext()

我认为你不一定需要ServletContext得到RequestDispatcher你可以打电话的HttpServletRequest.getRequestDispatcher().

关于FilterChain.doFilter()呼叫,如果你转发,我认为你不会拨打电话,因为一旦你转发,我认为你不希望任何标准行为发生.如果你不转发(你不属于你的if块),那么我会调用该FilterChain.doFilter()方法,但是假设在另一端有一个目标被调用.