I have a jsp servlet based application, with session time out of 30 mins, I want to invalidate the session as soon as a person closes the browser window intentionally or accidentally (OS shutdown/close from tast manager/powerdown)
Can I put a check for that and invalidate the session?
It is not possible to handle this scenario .
There are some browsers which provide this setting as their preference , but you can't handle this programitically.
At max:
You can make a poll from page(may be header) same as gtalk in gmail as soon as connection closes wipe that session out.
Why do you want to do that, you have already configured that in server that ,session should stay idle for 30 mins,after that it will expire in server.
if you want to do that use the following javascript or jquery(better for cross browser) , when the browse close event happens send an ajax request to invalidate session by running following code in jsp
(request.getSession(false).setMaxInactiveInteral(0);)
From javascript
<body onbeforeunload="doAjaxCall();">
(or)
jQuery(window).bind("beforeunload", function(){
// Do ajax request and dont wait for the response.
});
You can implement the server push ajax polling , for example think that session is going to expire in another 2 seconds , send a server side request to client to invalidate the cookie and also in the server you can invalidate the session.
if ( (getcurrentTime() - session.getCreationTime()) > 2000 ) {
}
While the page is rendered , get the maxinactiveinterval and then set the value to the JavaScript variable , then use setInterval function , pass the inactiveinterval value to function , once the timeout happens you can set the cookie to expire.
No I don't believe you can do that as there are no hooks available in the browser to get it to send a disconnect notification (of some sort) when it closes and I don't think there is a server-side mechanism to interrogate recent sessions to test their connection status.
If you are using tomcat 5.0/5.5/6.0 container, the cookie generated by tomcat session manager to track the session (JSESSIONID) is a per-session cookie (browser memory only cookie) instead of a persistent cookie (write to disk). That's because the session manager does (hardcoded) setMaxAge(-1), so that the generated HTTP-response contains:
Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; Path=/ and no Expire=date.
So when the browser is closed (all browser windows, or just the window containing the cookie, depending on the variuos browser implementations), the cookie - and the session - are lost. [*]
This has nothing to do with <session-timeout>, which is a setting that tells the tomcat server-side session manager to expire sessions when idle for more time than specified.
[*] they will still be persisted on disk on the server-side, till session-timeout expires, but there wont be a request with a cookie activating them.
Related
Ok, In Java, I don't understand what actions tell that a session is and isn't alive.
I used to think that if user has never touched the page and after a period of time, the session will expire.
session.setMaxInactiveInterval(15*60); //15 mins
But let say there is a page call ajaxChat.jsp which has a functions to send data back and forward between client and server.
The UserA logined & created a session. He then can enter the ajaxChat.jsp. UserB sometimes send messages to UserA via interface on ajaxChat.jsp.
UserA just lives the ajaxChat.jsp & do something else. Hoever, every 5 mins the UserB send a message to UserA.
The question is that if UserA just leaves ajaxChat.jsp there without touching it for more than 30mins, then will the session of User A expire? Note that every 5 mins, ajaxChat.jsp receives a new message from UserB.
I don't understand how Java Session works when it is counted that the session expires?
Which actions tell that a session is or isn't alive?
At which point of time is a session counted as inactive?
What if user has never touched the page but the page has some Ajax calls periodically in the background?
Here Ajax code in ajaxChat.jsp is responsible for sending and receiving the message. So both USer-A and User-B are using the output of the Servlet generated after JSP translation and compilation. So, do not think it as ajaxChat.jsp page is making communication between the two users.
For the server request that comes after every 5 minutes marking the activity from user irrespective of the call by normal user action or Ajax call. Both are equivalent for the server. Meaning that the server will not count it as inactive session.
If you want to have your application with behavior of expiring session after 15 minutes, you will need to handle on your own.
You can manage a map in application context (key as JSESSIONID cookie value) with your last activity time of user from the specific pages/calls which are interpreted as actions from the user not from Ajax Chat. Testing every time the difference (Last Activity Time - Current Time) and marking the session expired explicitly as sesion.invalidate().
In our JAVA web application we maintain users' session in a database table active_sessions. And we do not allow multiple sessions per user. what it means is, if you are already logged in with a particular user account, you cannot open a new session with the same account. In case somebody does, we display error 'User already has an active session'. When user clicks on Logout his entry from table active_sessions is removed. But in case where user closes the window without logging out his entry remains in the table active_sessions. So any attempt to login in future results in an error 'User already has an active session'. Any tips on how to destroy user session in database in case he closes the browser window without logging out.
Edit: After reading all the posts it seems there is no clean way to restrict single session per user.
Use the 'onbeforeonload' JavaScript event which can perform an AJAX call to your server to delete the entry. This event will however be executed each time the page is unloaded so if you don't have a SPA then you'll need to ignore the event for href and such.
Agree with Almas however that your approach is dangerous in the sense that it is not possible to enforce this 100%. E.g. if the user kills the browser process then even this JS event would not be published.
Furthermore, a user can simply use another browser to bypass your 'protection'.
In the server side users HTTP session is normally invalided after a certain period of idle time. You can implement http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpSessionListener.html and register it in web.xml to receive notifications about session create/destroy etc. In your listener implementation you could delete the table entry on session destroy event.
The basic thing about HTTP is that it is request/response protocol.
i.e. Things are changed/accessed only by making a request to the server. This 'limitation' makes your requirement interesting. There can be two workarounds for this:-
Poll the server at a repeated interval through an AJAX call. As long as you application keeps getting the polling AJAX request you can assume that the window is open.
Use javascript (window.onunload ) to fire an event to destroy user session when the browser is closed.
Using onuload
I am using timestamp till nano second as a user session, say tab A has session1 and user opens tab B say this session is session2 and now session1 gets only inactivated after some file upload activity is done at this point of time I want the session2 be still active.
How do I do this without using cookies?
have you looked into html5 sessionStorage/localStorage ?
these apis sport a client-side storage facility pretty similar to cookies which you can employ to manage sessions. the lifetime of the database is either the lifetime of the respective tab/window (ssessionStorage) or the interval between two consecutive deletions the pertaining browser data; the latter may depend on the browser preferences (eg. automatically after closing the tab/window in privacy mode or upon express user request).
for a start, mdn has something to say about it. there also is a full-fledged tutorial on html5rocks.
the gritty in-depth w3c standard details all about the programmatic (javascript) interface.
the api do not provide facilities to exchange information between client and server. one option to handle this part would be encoding the information into urls (client -> server) or http headers (server -> client) being called/received through ajax.
a final word of warning: for security reasons, do not store authenticating data this way.
say tab A has session1 and user opens tab B say this session is session2
This is already impossible. Both tabs will be in the same session. If tab B created a new session due to a login for example, tab A will now be in the new session.
and now session1 gets only inactivated after some file upload activity
It won't happen.
is done at this point of time I want the session2 be still active.
It still is. Session 1 will have been destroyed if it's different from session 2.
i wanted to throw an alert when session expires and when you press ok button in the alert box then it will take you to login page. For this i thought to create a timer and timertask and in the run method of the later class i will check if the session exists or not. So for this i tried to create a class in jsp page but it is showing error. i can create in servlet but all my pages are in jsp and so this idea is not useful.Now i created a sessionlistner and in the session destroyed method i want to link to login page but i have a problem here too.I can not use response method in the sessiondestroyed method.Please tell me are there any other ways
You can use JavaScript like:
var sessionTimeout = "<%= Session.Timeout %>";
function DisplaySessionTimeout()
{
//assigning minutes left to session timeout to Label
document.getElementById("<%= lblSessionTime.ClientID %>").innerText =
sessionTimeout;
sessionTimeout = sessionTimeout - 1;
//if session is not less than 0
if (sessionTimeout >= 0)
//call the function again after 1 minute delay
window.setTimeout("DisplaySessionTimeout()", 60000);
else
{
//show message box
alert("Your current Session is over.");
}
}
For more details visit here
First, you can creates totally client side solution: use setTimout() when page is loaded first time. Use either hard-coded or arrived from server value of timeout. When timer is triggered use document.location = login.html (or something like this) to arrive to login page.
This solution is "fast and dirty."
Better solution should be based on real session expiration. You can create AJAX call that tries from time to time special URL. This URL should return true/false that means that session is expired or not. When session is expired you should redirect the page to login screen. The problem with this solution is that the fact that you request the session state refreshes it. To solve this problem you can either perform the request to different server or (probably) remove session cookie from the polling request, so it will be performed in session different from the main session.
With Tomcat you can create a JS timer that make a simple AJAX call.
If the call return without errors the session is valid, if the call fails you can consider the session expired. On default behavior Tomcat deosn't renew sessions if you don't explicitly call it.
I had the opposit case: link
This problem is already solved by the Java EE Spec. You should consider using web.xml configurations to handle session timeout issues. It has specific tags for handling all of this. Some of the tags are:
<login-config> ... </login-config>
The above tag lets you used FORM based authentication where you can specify your login HTML resource.
<security-constraint> ... </security-constraint>
The above tag lets you specify the URLs you would like to secure. And finally the session timeout tag itself, which allows you to specify the session timeout in millis.
Once you do the above, the container would automatically take the user to the login page when he requests a secure URL.
Here is the web.xml reference.
From a messaging standpoint, there are multiple ways of seeing the problem:
The fact that system is taking the user back to the login page and forcing him to login, is indicator enough for him/her.
You could provide a generic message on the login page itself.
Device some tricky flag based or querystring logic to show the message on the login page.
Came across this link in StackOverflow itself which provides a strategy you can implement in the login page itself. Have not tried this though.
This in my mind is a trivial problem compared to the whole session timeout strategy itself.
Sorry for the broad topic. Basically, WSC is supposed to have out-of-the-box session timeout handling by forwarding the user to the ReLogonFormView, which the user can presumably configure (through Struts) to any jsp that they choose. We use a custom logoff command, and it seems to be affecting that view showing up.
I'm not looking for a specific solution to this problem, I'm just looking for general knowledge about how WSC (v6) handles session timeouts (how it determines that the session has timed out) and what command(s) it runs by default when / if / to determine the session has expired.
This is my current knowledge on this subject...
The session timeout is a global value for all web modules and can be found in the wc-server.xml and is set to 30 minutes OOTB.
When a timout occurs, the OOTB LogoffCmd would normally be called, which will set up the necessary URLs to navigate to the ReLogonFormView URL while keeping hold of the URL where the session timeout occurred.
If the ReLogonFormView contains userid/password fields to allow the user to logon again, the user will then be redirected back to the page they were originally on.
More info can be found in IBM InfoCenter under "LoginTimeout".
If you extend the OOTB LogonCmdImpl, you should not try and set the forwarding URL, or that will interfere with the OOTB navigation.
I think you should perform your custom logoff functionality and then call super.performExecute() to allow the OOTB navigation logic to take over.
Note: You can retrieve the URL you were originally on via a call to getReferrerURL() and the ReLogonFormView should be returned from getURL().