簡體   English   中英

來自過濾器的轉發請求

[英]Forward request from a filter

如果原始請求的URI通過我的過濾器運行的一些驗證,我需要從http.Filter 轉發我的請求 (到jsp,但我認為不重要)。

我發現這個頁面面臨着類似的任務

我仍需要計算以下內容:

  1. 如何在doFilter()方法中獲取ServletContext(為了調用轉發API) getServletContext()不重新簽名

  2. 我是否必須在前鋒之前call chain.doFilter() ,之后還是根本不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);

    }

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

httpServletRequest.getSession().getServletContext();

我是否必須在前鋒之前調用chain.doFilter(),之后還是根本不調用? 另外,如果我的驗證通過,或者僅當它失敗時,我必須調用chain.doFilter()(因為在這種情況下我不會繼續轉發我的頁面)?

我會說如果你轉發請求,你不應該調用chain.doFilter() - 轉發的請求將根據自己的過濾器配置進行過濾。 如果驗證失敗,則取決於您的Web應用程序的語義是什么 - 如果原始頁面是某種常規錯誤/登錄/歡迎屏幕,您可能希望在驗證失敗時繼續執行此操作。 如果不了解更多背景,很難說。

要獲得ServletContext ,您有兩個選擇:

  • 在初始化期間存儲FilterConfig並調用FilterConfig.getServletContext()

  • 調用HttpServletRequest.getSession().getServletContext()

我認為你不一定需要ServletContext來獲取RequestDispatcher因為你可以調用HttpServletRequest.getRequestDispatcher()

關於FilterChain.doFilter()調用,如果你正在轉發,我認為你不會進行調用,因為一旦你轉發,我認為你不希望發生任何標准行為。 如果你不轉發(你不屬於你的if塊),那么我會調用FilterChain.doFilter()方法,但是這假設在另一端有一個目標被調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM