如何在JSP EL中检查会话? [英] How to check for session in JSP EL?

查看:85
本文介绍了如何在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 是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);

那么你应该宁愿拦截:

<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆