maks
maks

Reputation: 6006

How can I check whether session was timed out?

How can I check in an error page whether the session was timed out?

I have tried

<c:choose>
    <c:when test="${empty pageContext.request.session}">
        //do smth
    </c:when>
    <c:otherwise>
        //do smth
    </c:otherwise>
</c:choose>

but it doesn't work.

Upvotes: 2

Views: 2605

Answers (3)

BalusC
BalusC

Reputation: 1109635

There is really no reliable way to detect that. You could fiddle with some session based token as request parameter in all links/forms and validate it in the filter, but that's fully spoofable and not really SEO friendly.

Best what you could do is to add a <meta http-equiv="refresh"> tag to the <head> of the master template which redirects the page to the session timeout error page automatically whenever the session is expired. Since you're using a shared error page, you could pass the condition as a request parameter:

<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval};url=error.jsp?type=timeout" />

and check it in the error.jsp as follows:

<c:choose>
    <c:when test="${param.type == 'timeout'}">
        <p>Your session has been timed out.</p>
    </c:when>
    <c:otherwise>
        <!-- Handle default case here. -->
    </c:otherwise>
</c:choose>

Oh, yes, ${pageContext.session} is legitimately valid. The ${pageContext.request.session} is just an unnecessary detour. Check the PageContext javadoc for all available getters.

Upvotes: 2

Ramesh PVK
Ramesh PVK

Reputation: 15456

request.getSession() will always return session, thus your approach will not work. If your requirement is not create a session, when does not exist, use a custom tag.

If you want to create a session when it does not exist, and you want to know if the the request is joining the session/creating a new session. Use ${pageContext.request.session.new}.

Upvotes: 0

Dave G
Dave G

Reputation: 9777

I don't think that will work the way you want. try ${pageContext.request.session.new}

If you don't specify in the <%@page session="false"%> tag I don't think it creates a new session so your first code /might/ work but I would stress checking in the fashion I indicated above.

.isNew() is defined on HttpSession

Upvotes: 0

Related Questions