【问题标题】:Forward request from a filter转发来自过滤器的请求
【发布时间】:2011-03-25 19:42:12
【问题描述】:

我需要转发我的请求(到 jsp,但我认为这无关紧要)来自 http.Filter 如果原始请求的 URI 通过了我的过滤器运行的一些验证。

我找到了这个page that faced similar task

我还需要弄清楚以下几点:

  1. 如何在doFilter() 方法中获取ServletContext(以便调用转发API)getServletContext() 不被识别

  2. 我必须在转发之前、转发之后还是根本不需要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);

    }

【问题讨论】:

    标签: java jakarta-ee filter


    【解决方案1】:

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

    httpServletRequest.getSession().getServletContext();
    

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

    我会说,如果您转发了请求,则不应调用chain.doFilter() - 转发的请求将根据其自己的过滤器配置进行过滤。如果您的验证失败,这取决于您的网络应用程序的语义是什么 - 如果原始页面是某种一般错误/登录/欢迎屏幕,您可能希望在验证失败时继续进行。不了解更多上下文就很难说。

    【讨论】:

      【解决方案2】:

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

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

      • 致电HttpServletRequest.getSession().getServletContext()

      我认为您不一定需要ServletContext 来获取RequestDispatcher,因为您可以调用HttpServletRequest.getRequestDispatcher()

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

      【讨论】:

      • 两个答案都很好。另一个是第一个。
      • 在初始化期间存储 FilterConfig 并调用 FilterConfig.getServletContext() 这是我的首选方法,因为没有明确的会话:
      猜你喜欢
      • 2015-09-12
      • 1970-01-01
      • 2020-03-09
      • 2021-08-18
      • 2013-08-10
      • 2018-05-25
      • 2011-10-04
      • 2013-09-23
      • 1970-01-01
      相关资源
      最近更新 更多