I'm trying to timeout an HttpSession in Java. My container is WebLogic.
Currently, we have our session timeout set in the web.xml file, like this
<session-config>
<session-timeout>15</session-timeout>
</session-config>
Now, I'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
I'm wondering if this approach is the correct one, or should I programatically set the time limit of inactivity by
session.setMaxInactiveInterval(15 * 60); //15 minutes
I don't want to drop all sessions at 15 minutes, only those that have been inactive for 15 minutes.
Are these methods equivalent? Should I favour the web.xml config?
Please check seession timeout in below pseudo code
No, that's not true. The
session-timeout
configures a per session timeout in case of inactivity.The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The
HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as<session-timeout>
inweb.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been astatic
method).To play around and experience this yourself, try to set
<session-timeout>
to 1 minute and create aHttpSessionListener
like follows:(if you're not on Servlet 3.0 yet and thus can't use
@WebListener
, then register inweb.xml
as follows):Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see
destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.See also: