I need to end the session automatically when the user is inactive for some particular time say for 10 minutes. We have a method in
HttpSession session=reque
You need to set the session timeout, that is, the time after which current Session
object will be invalidated.
This can be done either by setting timeout in your web.xml like:
<session-config>
<session-timeout>20</session-timeout>
</session-config>
or programmatically call on the Session
object
session.setMaxInactiveInterval(valueInSeconds);
Keep an eye that session timeout period set up in web.xml is in minutes, and programmatically - in seconds.
Question: How to end sessions automatically if user closes the browser?
Answer: Set max inactive interval time value less than 0.
Example:
HttpSession session = request.getSession();
session.setMaxInactiveInterval(-1);
session.setAttribute("User", au);
response.sendRedirect("doLogin.jsp");
You can do that from web config file. A sample is here
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"
sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
sqlCommandTimeout="30"
customProvider=""
cookieless="UseCookies"
cookieName="ASP.NET_SessionId"
timeout="10"
allowCustomSqlDatabase="false"
regenerateExpiredSessionId="true"
partitionResolverType=""
useHostingIdentity="true">
<providers>
<clear />
</providers>
</sessionState>
The timeout property will specify the timeout period.
You can set the session time out as below in the ServletContextListener:
session.setMaxInactiveInterval(15*60); //in seconds
This will give you the advantage that you can read the session timeout from any external properties file/ database and change the session timeout without changing the code.
You can use the unload event and send the logout request to the server. Or keep sending periodic requests to the server informing the user is still active.
There is no way to intimate the server about the user closes the browser. That's why the sessions are having configurable timespan. If you wanna do it then try by creating a onclose javascript event and from there do an ajax call to intimate the session close to the server. In the server you can get the session id from this call as parameter and kill it.
I didn't tried it. Don't think it is right to do.
Avoid manual code for that.
simply in web.xml
//this will applied for whole application
<session-config>
<session-timeout>10</session-timeout>
</session-config>
Detect browser close event and call invalidate method
if(session!=null) {
session.invalidate();
}