首先讓我描述一下我正在嘗試做什麼,我猜測它非常簡單。 我有一個網站與用戶,並希望限制訪問一個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中做某些事情,我完全迷失在這裏。
感謝您的答案。我已經將css的路徑更改爲,但是會發生什麼呢?它會在一秒鐘內請求'localhost:8080/auth/css/styles.css',然後再次通過過濾器,然後發出css請求完全消失。結果是一樣的。 –
michauwilliam
路徑必須是絕對路徑:以'/'開頭。 –
謝謝:) Css的作品。但是,我應該如何處理頁面上的鏈接?無論如何要讓它們不指向/ auth/context?我已經嘗試了但它仍然指向/auth/logout.jsp –
michauwilliam