Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

java - How to check for session in JSP 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's indeed never null. The session is always present in JSP EL, unless you add

<%@page session="false" %>

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>

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>

(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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...