如何检查 EL 中请求的 session 是否存在?我正在尝试类似的东西:
<c:if test="${pageContext.request.session != null}"> ... </c:if>
但它似乎永远不会为空。
最佳答案
它确实永远不会是null
。 session 总是存在于 JSP EL 中,除非您添加
<%@page session="false" %>
到 JSP 的顶部。然后您可以按如下方式检查 session (仅限 EL 2.2!):
<c:if test="${pageContext.request.getSession(false) != null}">
<p>The session has been created before.</p>
</c:if>
我不确定具体的功能需求是什么。如果您想检查 session 是新 session 还是已创建,请使用 HttpSession#isNew()
相反。
<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 语言中的保留文字)
如果您依赖于特定 session 属性,例如设置为的已登录用户
session.setAttribute("user", user);
那么你应该拦截它:
<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>
关于java - 如何检查 JSP EL 中的 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135725/