2010-06-04 70 views
11

在我的web應用程序中,我需要檢查會話是否已經存在。在servlet和jsp中檢查會話

我想在我的servlet和jsp中檢查這一點。

有沒有什麼辦法來檢查這個。

感謝

回答

13

您可以用HttpServletRequest#getSession(boolean create)create=false進行測試。如果尚未創建,它將返回null。

HttpSession session = request.getSession(false); 
if (session == null) { 
    // Session is not created. 
} else { 
    // Session is already created. 
} 

如果你真的想反正創建會話,如果不存在的話,那麼就抓住它,並使用HttpSession#isNew()測試新鮮感:

HttpSession session = request.getSession(); 
if (session.isNew()) { 
    // Session is freshly created during this request. 
} else { 
    // Session was already created during a previous request. 
} 

這是你會怎麼做它在一個Servlet的。在JSP中,您只能在JSTL和EL的幫助下測試新鮮度。您可以通過PageContext#getSession()獲取會話,然後只需撥打isNew()即可。

<c:if test="${pageContext.session.new}"> 
    <p>Session is freshly created during this request.</p> 
</c:if> 

<p>Session is ${pageContext.session.new ? 'freshly' : 'already'} created.</p> 
2

一種方式是設定在JSP中的會話ID,然後檢查相同的會話ID在其他JSP或Servlet來檢查它是否還活着與否。

HttpSession session = req.getSession(); 
     session.getId();