2010-08-05 57 views
13

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

我發現這個page that faced similar task

我仍然需要計算如下:

  1. 我怎樣才能獲得的ServletContext在doFilter()方法(以呼叫轉移API)getServletContext()不recignized

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

    } 

回答

10

如何我的doFilter得到的ServletContext()方法?

httpServletRequest.getSession().getServletContext(); 

我必須前進之前調用chain.doFilter(),之後向前或不呢?另外,如果我的驗證通過了,或者只有在失敗時才需要調用chain.doFilter()(因爲在這種情況下,我不會繼續轉發我的頁面)?

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

10

要獲得ServletContext,你有2個選擇:在初始化過程中

  • 商店關閉FilterConfig和呼叫FilterConfig.getServletContext()

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

我不t認爲你一定需要ServletContext才能得到RequestDispatcher因爲您可以撥打HttpServletRequest.getRequestDispatcher()

關於FilterChain.doFilter()打電話,如果您正在轉發,我認爲您不會打電話,因爲一旦您轉發,我假設您不希望發生任何標準行爲。 如果你沒有轉發(你不會陷入你的if塊),那麼我會打電話給FilterChain.doFilter()方法,但是假設在另一端有一個目標被調用。

+0

這兩個答案都很好。另一個是第一個。 – Spiderman 2010-08-09 07:01:32

+0

在初始化過程中關閉FilterConfig並調用FilterConfig.getServletContext()這是我首選的方法,因爲沒有明確的會話: – Gurnard 2012-11-07 13:36:10