[英]How to properly invalidate JSP session?
所以這就是問題所在。 當用戶退出我的網站時,他們仍然可以點擊后退按鈕並繼續使用該網站。 為了跟蹤用戶是否登錄,我創建了一個會話屬性“isActive”。 用戶登錄時該屬性設置為true,並且在注銷時會話無效之前(冗余)刪除該屬性。 同樣在每個頁面上,我都會檢查屬性是否存在。
我還指定不應在其head標簽中緩存頁面。
盡管如此,用戶仍然能夠回擊瀏覽器,並繼續使用該網站,就好像他們從未注銷過一樣。
有關如何解決此問題的任何想法?
這是代碼:
登錄Servlet:
...
session.setAttribute("isActive", true);
//Redirect to home page.
檢查登錄的JSP:
<c:if test='${empty sessionScope.isActive || sessionScope.isActive != true}'>
<c:redirect url="/index.jsp?message=Session Timed Out."/>
</c:if>
注銷Servlet:
request.getSession().removeAttribute("isActive");
request.getSession().invalidate();
response.sendRedirect("index.jsp");
內部標記:
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
謝謝
元標記是不夠的。 您需要將它們添加為完整的響應標頭。 webbrowser依賴於它們。 Filter
對此有幫助。 此外, Cache-Control
標頭不完整(在Firefox等中無法正常工作)。
在Filter
的doFilter()
方法中實現它,該方法映射在例如*.jsp
的url-pattern
上(如果要覆蓋所有JSP頁面)。
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(request, response);
這樣,webbrowser將被強制在服務器上發出實際請求,而不是從瀏覽器緩存中顯示頁面。 此外,您應該使用Filter
來檢查登錄用戶的存在,而不是JSP / JSTL。
您不應該檢查會話頁面上的會話是否仍處於活動狀態,最好使用Filter
進行檢查。
如果在過濾器中, request.getSession().getAttribute("isActive")
返回一些東西,那么用戶仍然會被記錄,你只需鏈接; 否則你在登錄頁面上重定向。
例如 :
public class ActiveFilter implements Filter {
public void init(FilterConfig filterConfig)
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (req.getSession().getAttribute("isActive") == null){
res.sendRedirect("/index.jsp");
}else{
chain.doFilter(request, response);
}
}
}
資源:
我的所有JSP都有no-cache標頭(通過@include指令)。 我在應用程序的根目錄中有一個logout.jsp ,其中包含以下行:
HttpSession sessIfAny = request.getSession(false);
if (sessIfAny != null) sessIfAny.invalidate();
這可以防止創建不必要的會
web.xml需要從身份驗證中免除logout.jsp:
<!-- Resources excepted from authentication -->
<security-constraint>
<web-resource-collection>
<web-resource-name>excepted</web-resource-name>
<url-pattern>/logout.jsp</url-pattern>
<url-pattern>/favicon.ico</url-pattern>
<!-- ... other resources -->
</web-resource-collection>
<!-- no auth-constraint -->
</security-constraint>
這可以防止顯示登錄頁面在過期的會話上進行注銷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.