在我的Web应用程序中,我需要检查会话是否已存在。
我想在我的servlet和jsp中检查这个。
有没有办法检查这个。
谢谢
在我的Web应用程序中,我需要检查会话是否已存在。
我想在我的servlet和jsp中检查这个。
有没有办法检查这个。
谢谢
你可以测试一下 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>
一种方法是在jsp中设置会话ID,然后在另一个jsp或servlet中检查相同的会话ID,以检查它是否存活。
HttpSession session = req.getSession();
session.getId();