如何在 JSP EL 中检查会话? [英] How to check for session in JSP EL?
问题描述
如何检查EL中的请求是否存在会话?我正在尝试类似的东西:
How do you check if a session exists for the request in EL? I'm trying something like:
<c:if test="${pageContext.request.session != null}"> ... </c:if>
但它似乎永远不会为空.
but it seems like it's never null.
推荐答案
确实永远不会null
.会话总是出现在 JSP EL 中,除非添加
It's indeed never null
. The session is always present in JSP EL, unless you add
<%@page session="false" %>
到 JSP 的顶部.然后,您可以按如下方式检查会话(仅限 EL 2.2!):
to top of JSP. You could then check for the session as follows (EL 2.2 only!):
<c:if test="${pageContext.request.getSession(false) != null}">
<p>The session has been created before.</p>
</c:if>
我不确定具体的功能要求是什么.如果您想检查会话是新会话还是已经创建,请使用 HttpSession#isNew()
.
I'm not sure what's the concrete functional requirement is. If you'd like to check if the session is new or has already been created, use HttpSession#isNew()
instead.
<c:if test="${not pageContext.session['new']}">
<p>You've already visited this site before.</p>
</c:if>
<c:if test="${pageContext.session['new']}">
<p>You've just started the session with this request!</p>
</c:if>
(new
的大括号符号是强制性的,因为 new
是 Java 语言中的保留字面量)
(the brace notations for new
are mandatory because new
is a reserved literal in Java language)
如果您依赖于特定会话属性,例如设置为的登录用户
Of if you're relying on a specific session attribute, such as the logged-in user which is been set as
session.setAttribute("user", user);
那么你应该拦截它而不是:
then you should rather be intercepting on that instead:
<c:if test="${not empty user}">
<p>You're still logged in.</p>
</c:if>
<c:if test="${empty user}">
<p>You're not logged in!</p>
</c:if>
这篇关于如何在 JSP EL 中检查会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!