How to check session in JSP EL?

How do you check if a session exists for a request in EL? I'm trying something like:

<c:if test="${pageContext.request.session != null}"> ... </c:if> 

but it seems that he was never zero.

+4
java jsp session el
source share
3 answers

It really is never null . A session is always present in JSP EL , unless you add

 <%@page session="false" %> 

to the top of the JSP. Then you can check 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 am not sure what a specific functional requirement is. If you want to check if the session is new or has already been created, use 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> 

(the binding notation for new is mandatory, since new is a reserved literal in Java)

If you rely on a specific session attribute, for example, a registered user that has been set as

 session.setAttribute("user", user); 

then you better intercept this:

 <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> 
+11
source share

Seems to work with:

 <c:if test="${fn:length(sessionScope) > 0}"> 

I wonder if there is a better way, since it requires that I have session attributes (I always do this, but it's not very clean)?

+1
source share

J2EE will always have a session object when a user visits a site.

What is a session? The session is largely reminiscent of what sounds when a user makes a page request to a server, the server creates a temporary session to identify that user. Therefore, when the same user goes to another page on this site, the server identifies this user. Thus, the session is a small and temporary unique connection between the server and the user, allowing him to identify this user through several page requests or visits to this site.

So basically, if you click on a page, you have a session because you are using JSP, which will eventually be converted to servlets.

http://www.stardeveloper.com/articles/display.html?article=2001062001&page=1

+1
source share

All Articles