2012-01-27 47 views
2

我有一個過濾器來處理請求以便記錄它們,所以我可以跟蹤哪個會話在什麼時間點擊了哪個會話以及請求參數。非常棒......從jsp發佈到jsp,或直接調用jsp。但是,當一個表單發佈到將該請求轉發給新的jsp的servlet上時,我無法查看該請求轉發給了哪個jsp。如何從過濾器中確定jsp從RequestDispatcher.forward調用轉發到哪裏?

例如,假設我有一個登錄頁面,該頁面發佈到LoginServlet,然後將請求轉發給index.jsp或index1.jsp。我如何從請求中確定LoginServlet是否返回i​​ndex.jsp或index1.jsp?

這是在使用2.3 servlet規範的java 1.5環境中。

public class PageLogFilter implements Filter { 

    FilterConfig filterConfig = null; 

    public void init(FilterConfig filterConfig) throws ServletException { 
     this.filterConfig = filterConfig; 
    } 

    public void destroy() { 
     this.filterConfig = null; 
    } 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
      throws IOException, ServletException { 
     try { 
      if (request instanceof HttpServletRequest) { 
       HttpServletRequest req = (HttpServletRequest) request; 
       HttpSession session = req.getSession(false); 

       //For non-forwards, I can call req.getRequestURI() to determine which 
       //page was returned. For forwards, it returns me the URI of the 
       //servlet which processed the post. I'd like to also get the URI 
       //of the jsp to which the request was forwarded by the servlet, for 
       //example "index.jsp" or "index1.jsp" 
      } 
     } catch (Exception e { 
      System.out.println("-- ERROR IN PageLogFilter: " + e.getLocalizedMessage()); 
     } 

     chain.doFilter(request, response); 
    } 
} 
+0

可能重複[如何從一個過濾器,網頁服務從RequestDispatcher的正向確定?](http://stackoverflow.com/questions/9011106/how-to-determine-from-a-filter-which-page-serviced-a-forward-from-requestdispatc) – Bozho 2012-01-27 19:34:37

回答

2

如果您可以執行額外的檢查,那麼您可以使用attribute來設置/獲取原始請求URI。 在你LoginServlet設置屬性:

//LoginServlet 
public void doFilter(...) { 
     HttpServletRequest oReq = (HttpServletRequest)request; 
     .. 
     ... 
     //save original request URI 
     oReq.setAttribute("originalUri", oReq.getRequestURI()); 
} 

,並在您PageLogFilter檢查,如果originalUri屬性有值,則認爲該值作爲請求URI

//PageLogFilter 
public void doFilter(...) { 
     HttpServletRequest req = (HttpServletRequest) request; 
     if(req.getAttribute("originalUri") != null) { 
      String strOriginalUri = (String) req.getAttribute("originalUri"); 
      //set it back to null 
     req.setAttribute("originalUri", null); 
     } 
} 
+0

Thans Waqas,這將一定會工作,如果沒有其他解決方案出現,我會執行它。有沒有其他方式可以做到這一點,而不必將該代碼添加到我寫的每個servlet? – rpierce 2012-01-27 16:29:15

0

雖然它不會幫助您解決眼前的問題,Servlet的2.4在調度器上添加了更多的詳細控制,這正是你想要的。

有了它,您可以配置過濾器以添加以下調度程序元素,這將導致過濾器也適用於轉發。

<filter-mapping> 
     <filter-name>PageLogFilter</filter-name> 
     <url-pattern>/*</url-pattern> 
     <dispatcher>FORWARD</dispatcher> 
</filter-mapping> 

下面的文章介紹比較詳細

http://www.ibm.com/developerworks/java/library/j-tomcat2/

相關問題