2010-06-04 67 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();