在servlet和jsp中检查会话 [英] checking session in servlet and jsp
问题描述
在我的网络应用程序中我需要检查会话是否已经存在。
In my web application i neet to check session already exist or not.
我想在我的servlet和jsp中检查这个。
i want to check this in my servlet and in jsp also.
有没有办法检查这个。
谢谢
推荐答案
您可以使用 HttpServletRequest#getSession(boolean create)
, create = false
。如果尚未创建,它将返回null。
You can test it with HttpServletRequest#getSession(boolean create)
with create=false
. It will return null if not created yet.
HttpSession session = request.getSession(false);
if (session == null) {
// Session is not created.
} else {
// Session is already created.
}
如果你确实想要创建会话,如果它不存在,然后抓住它并使用 HttpSession#isNew()
:
If you actually want to create the session anyway if it doesn't exist, then just grab it and test the freshness using 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()
。
That was how you would do it in a Servlet. In a JSP you can only test the freshness with help of JSTL and EL. You can grab the session by PageContext#getSession()
and then just call isNew()
on it.
<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>
这篇关于在servlet和jsp中检查会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!