2012-01-20 25 views
2

首先讓我描述一下我正在嘗試做什麼,我猜測它非常簡單。 我有一個網站與用戶,並希望限制訪問一個view_profile.jsp頁面只記錄用戶。我有一個過濾器映射到:經過Java Filter後,使用RequestDispatcher進行轉發

<url-pattern>/auth/*</url-pattern> 

它看起來像這樣

 try { 
     HttpSession session = ((HttpServletRequest)request).getSession(); 
     UserBean user = (UserBean)session.getAttribute("currentUser"); 
     if (user != null && user.isValid()){ 
      System.out.println("Filter: context -> " + ((HttpServletRequest)request).getContextPath()); //returns "" 
      chain.doFilter(request, response); 
     } 
     else{ 
      ((HttpServletResponse)response).sendRedirect("/login.jsp"); //works fine 
     } 

此過濾器上運行index.jsp頁面時用戶會點擊一個鏈接:

<a href="./auth/view_profile?profile=${sessionScope.currentUser.username}"> 
//yeah, he will 'view' himself - it's just an example 

這是假設用戶將映射到ViewProfileServlet的servlet映射到:

<url-pattern>/auth/view_profile</url-pattern> 

它看起來像這樣:

try { 
     String username = (String) request.getParameter("profile"); 

     // here is getting info from database and setting request attributes 
     // works fine 

       //response.sendRedirect("/view_profile.jsp"); 
       System.out.println("ViewProfileServlet: In context -> " + getServletContext().getContextPath()); // returns "" 
       dis = getServletContext().getRequestDispatcher("/view_profile.jsp"); 
       // i've tried request.getRequestDispatcher. no difference 
       System.out.println("ViewProfileServlet: forward to '/view_profile.jsp'"); 
       dis.forward(request, response); 
      } 

而這又應該採取用戶到/view_profile.jsp(在根上下文,而不是在/ AUTH)和工作,它沒有。 ViewProfileServlet會運行並顯示view_profile.jsp,儘管看起來上下文仍然是/ auth,因爲view_profile.jsp上的所有鏈接都指向localhost:8080/auth/some-page.jsp。另外,css文件沒有被加載,它們甚至沒有被請求(至少根據螢火蟲),並且頁面源顯示404 Glassfish錯誤,其中css應該是。

我非常感謝任何幫助,這是我第一次在jsp中做某些事情,我完全迷失在這裏。

回答

3

轉發發生在服務器端。瀏覽器不知道它。當它向/auth/view_profile發送請求並從此響應接收到HTML時,他不關心這些HTML是由servlet,JSP,兩者還是其他任何東西生成的。它讀取HTML並認爲它來自路徑/auth/view_profile。因此HTML中的所有相對路徑都是相對於/auth/view_profile

它更容易使用絕對路徑參考圖像,JS和CSS路徑(甚至其他行爲,大部分的時間)。只需確保使用<c:url>標記生成URL,以便前置Web應用的上下文路徑:

<script src="<c:url value='/js/myScript.js'/>" type="text/javascript"/> 
          ^-- the slash here makes the path absolute. 
+0

感謝您的答案。我已經將css的路徑更改爲,但是會發生什麼呢?它會在一秒鐘內請求'localhost:8080/auth/css/styles.css',然後再次通過過濾器,然後發出css請求完全消失。結果是一樣的。 – michauwilliam

+0

路徑必須是絕對路徑:以'/'開頭。 –

+0

謝謝:) Css的作品。但是,我應該如何處理頁面上的鏈接?無論如何要讓它們不指向/ auth/context?我已經嘗試了但它仍然指向/auth/logout.jsp – michauwilliam