retrieve logout time without logout - java

how can i see logout time when user closes the browser without logout?
So i implemented HttpSessionBindingListener taken from here and added Listener in web.xml but logout time is not being inserted into database after closing browser. Any suggestion please where i am wrong?
logout.jsp
<%
ObjectWillBeInSession owi = new ObjectWillBeInSession();
owi.setProperty1("I am a value for Property1");
owi.setProperty2("I am a value for Property2");
//this will call HttpSessionBindingListener's
//valueBound method for the object
session.setAttribute("owi", owi);
//this will call HttpSessionBindingListener's
//valueUnbound method for the object
session.removeAttribute("owi");
//INSERT INTO DB.......BUT IT IS NOT WORKING
%>

Closing the browser does not trigger any request to the server, so there is no way you can know that the user closed his browser.
You can use a listener to way for the session to time out and then store the current time when that happens. Session typically expire hours after the last request from the client, though.

You can use JavaScript's window.onbeforeunload to send an AJAX request to a servlet to record the time the user closed the browser and do what you need in the session object.

Related

At which point of time is a session counted as inactive?

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().

Destroy user session stored in database on window close

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

How to logout automatically after session timeout on server in java web application

I have a small web application with simple requirement that, I have a servlet and few JSP pages in my application.
When ever we give request to sevrlet it starts session on server with session timeout 1minute, then it displays one JSP page.
After session timeout on server I want to automatically display sign out JSP page in the browser how can we achieve this.
To add to Jhash
You have to have a timer javascript function on every jsp of your application (you can keep it in a .js file and include it)
Your session on the server can be about 30 minutes and your javascript timer can be around 2 to 5 minutes because even if a cached html page is shown, it would find out the situation within 2 minutes
Hope you are not relying on this for securing the application. You should still check on serverside that the user session is valid before letting the user use your application (the javascript should be only for convenience)
Edit:
Example of guessing timeout in JS and then navigating the user out:
var lastActiveTimeMs = new Date().getTime(); //This is set to current time on page load
var SESSION_TIMEOUT_MILLIS = 35*60*1000; //35 mins in milliseconds
var CHECK_TIME_MILLIS = 60*1000; //1 mins in milliseconds
setTimeout(fnCheckTimeout, CHECK_TIME_MILLIS); //Check the timeout once in a minute
function fnCheckTimeout(){
var curMs = new Date().getTime();
if( (curMs-lastActiveTimeMs)>SESSION_TIMEOUT_MILLIS ){
window.location.href = 'signout.html';
}
}
//Keep updating lastActiveTime every time you do an Ajax call.
//Because server will keep extending the session for every page load or ajax call from client
For this you need to use javascript in your jsp page.
For example if your session timeout is 2 minutes on server, in JSP page also you need to create a timer with same time using javascript, after javascript timer timeout happens, you just need to refresh the page by using same javascript code. so when you refresh the page session timeout happened already on server so you can check for session on server and if session is expired redirect control to the page you want.

how to send an alert when session expires

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.

Invalidate a session

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.

Categories