How to Delete data from Database upon closing the browser - java

When a user logs in to my web app, I create a session:
session.setAttribute("SessionNumber","100");
And his username is added to a table named ONLINE_USERS.
Other Online users will be able to see him, they see all online users
When the user clicks on the log out button, I delete that row from the table, then I delete the session using:
session.invalidate();
But let's say the user existed the browser, his session will be gone, but the row will stay in the database as an online user, how to avoid this?
I'm using JSP-Servlets on Netbeans.

You can enable a custom HttpSessionListener to delete the table row upon session invalidation.
public class YourHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
//put row in the database
}
public void sessionDestroyed(HttpSessionEvent event) {
//delete the row from database
}
}
Declare the listener in your web.xml:
<listener>
<listener-class>YourHttpSessionListener</listener-class>
</listener>
Note that there will be a delay between the moment the user exits the browser and his session expires on the server. But session expiration time is configurable. You should find a suitable expiration timeout: not too long so you don't display for too much offline users as online, but not too short to allow connected users an idle period.
I think this is a good trade off for a chat application developed with basic servlet and jsp technology.

As I understand you want see users that are operating on web site at the moment, problem with HttpSessionListener is that session can live quite long before its destroyed, so it can happen that the user is not using the web site long time when it is destroyed.
(see http://www.smartsoftwarebits.com/qaa/46-misc/82-how-to-set-session-timeout-for-tomcat )
Solution: You can add a column to the database where you will store the time stamp of the last request
which user made. To keep this column up to date use a servlet filter. ( http://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html )
To clear online users add a timer job (for example using quartz) where you will delete rows (online users) that are older than (for example) 5 minutes (thus when last interaction is older than 5 mins.) ( http://quartz-scheduler.org/ )
Using this you will now quite precisely if there is user is "still there" or not.
In addition you can add a timer to client side javascript to make an ajax call periodically. You can handle this way the situation when user did not close the browser just were inactive for a while.

First thing is to catch the event when the browser is closed
You can try below code snippet in your jsp to hit a js function which will call an ajax function to hit server side component. Then simply use the session API to invalidate the session and add the code to delete the record from the table.
window.onbeforeunload = WindowClose;
function WindowClose() {
//Write a AJAx request here to hit the server side servlet to invalidate the session
}
Or use
<body onunload="WindowClose(); >
In the server side code , use
HttpSession session = request.getsession();
session.setMaxInactiveInterval(0); //or session.invalidate();
It will be good approach to define default session timeout value in the web.xml so that incase browser crashes, sessions will invalidate after the stipulated amount of time has passed.
<session-config>
<session-timeout>30</session-timeout>
</session-config>

Related

HttpRequest object after session times out for a web application

I wanted to know how request objects behave when a session is time out.
To be more specific I came across to one scenario, for which I am not able to figure out what is happening exactly.
The scenario is like this,
I have a login page for my web application with username and password fields. I have set the time out to 10 minutes for my app.
I am on the login page doing nothing for 15 minutes, so the session is timed out.
Now on the login I put the user name and password and hit submit. The page is getting refreshed instead of submitting.
So can I say upon session time out,the request object also times out?
Since you do not add any code to your question, my explanations should be taken with a grain of salt.
IMHO, you are starting the session when a client requests the login page (before he submits the login page) and also you've set it so that a request belonging to a timeout session will be redirected to login page.
So if the result is not to your liking you have to change some of the above.
But again, for a better answer, you have to show us some code.
And for your question about request time out. No it did not time out. It only times out if the server does not respond in time (which is a different kind of time out)
I added some Java code partials which I am using to direct requests belonging to sessions which are timed out to Login page. By the way I also should add that requests which did not require a session is handled before this redirection.
HttpSession session = request.getSession(false);
boolean hasActiveSession;
if (session == null) {
hasActiveSession = false;
//...
}
//...
if (!hasActiveSession) {
request.setAttribute("alert","Your session has timed out");
request.getRequestDispatcher("/WEB-INF/Login.jsp").forward(request, response);
}

How to Logoff user when a user logsIn some where else

I am trying to implement the functionality with which , when a user is loggedIn at one place and when he try to login to some where else , He should automatically be LoggedOut from the previous place .
Like in GMAIL..
If some one can give me the concept , As i think I need to save the user LoggedIn Status in Db,As sessions doesnt looks to be heplful. But then I dont understand how we update user status in DB ,if there is no activity for lets say 5 minutes (how will i capture the inactivity and updating in db).
If some one can please guide, I am struggling on this for hours now .
Thanks
When user login add the user session with id to a hashmap. When the same user logins again check for entry in the HashMap and if available invalidate the session and create new session for the user.
If you are using Spring Security, it provides this functionality out of the box.
Otherwise:
Create a java.util.Map (A ConcurrentMap is prefered, so manipulating it concurrently won't corrupt it), and stores it in application scope (ServletContext).
Now, you shall store each user and a reference to its session upon login in the map, and if a user logins again, just fetch previous session object and invalidate it.
Now implement an instance of javax.servlet.http.HttpSessionListener, and in void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent); method, remove the specified session from the Map. (This listener is invoked on session invalidation, whether it is done automatically by container or if you do it programmatically). just register this listener in web.xml and everything is done.
p.s. I know that it will be some-how harder, if you are deploying your application on a cluster of web-containers, but when you have just one server, that's ok.
p.s. I don't recommend storing session information in DB.

how to get user logout time when user closes the web browser without logging out from application [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have created web application that handle user login with it and update logout time when user logout from application, but when user close web browser directly or system gone shutdown with some problem, i am not able to update user logout time.
Please give any possible way to update user logout time on such circumstances.
Assuming javascript on client side as it is a webapp.
In such cases you should send a request in browser close event
window.onbeforeunload = function(event) {
//send request to server .
}
Prefer to read :want to detect browser close event?
May the following steps help you to update logout time.
1.Keep updating a timestamp variable in session for each request.
2.During session time out get the variable value (which holds when user accessed at last) and update in logout record.
This could help without depending the browser to send logout request.
try this code to implement
window.onbeforeunload = function(event) {
var isOK = confirm("Are you sure to Leave this Page?");
if(isOK)
{
// try ajax for update your table
}
}
You can create a class which implements HttpSessionListener and annotated #WebListener() like this:
#WebListener()
public class MyListener implements HttpSessionListener {
#Override
public void sessionCreated(HttpSessionEvent se) {
}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
Date lougOutDate=new java.util.Date();
}
}
in sessionDestroyed method you retrieve the date of disconnection
Why don't you use a TimeOut ?
There is several solutions :
Timeout
Implement HTTP COOKIE. Check the link below
http://en.wikipedia.org/wiki/HTTP_cookie
In your specific case it should be Session Cookie
Session cookie
A user's session cookie[14] (also known as an in-memory cookie or transient cookie) for a website exists in temporary memory only while the user is reading and navigating the website. When an expiry date or validity interval is not set at cookie creation time, a session cookie is created. Web browsers normally delete session cookies when the user closes the browser.[15][16]
Do the stuff with Javascript as suggested
Hope it's help :)
You could try to write some Javascript that sends an "User logging out" message to the server. This code should be triggered using $.unload() (if you're using jQuery) or binding to the native unloadevent of the browser.
There is no way of precisely getting the logout time in such circumstances, as this might be for example caused by internet connection loss.
Some possibilities:
Send an ajax request on document unload to notify your server (as suggested by #Baadshah and #mthmulders)
Add a session timeout listener on the server to set the logout time when the session times out - this way even if the ajax doesn't get to the server you will know that the user logged out during the last few minutes (depending on the session duration)
Use the event beforeunload with jquery on your page.
The beforeunload event fires whenever the user leaves your page for any reason.
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
var inFormOrLink = false;
$(document).on('click','a', function() { inFormOrLink = true; });
$(document).bind('submit','form', function() { inFormOrLink = true; });
$(window).on('beforeunload',document, function(eventObject) {
var returnValue = undefined;
if (inFormOrLink == false) {
//do your action
}
});
EDIT: Answer found here: How to capture the browser window close event?

Session Manegement using java

I am using jboss server. As of now my users getting logged out when my server bounces. On that time time I won't allow them to log out. How to manage this session even my server bounces.
Whenever you restart your server all user sessions will be lost. If you still want to keep user sessions then use cookies to maintain user sessions instead of thing like HttpSession.
When user logged in keep its session and also maintain a cookie. When server restarts check if cookie present. If its there then allow user to access resources.
You can set cookie as: For this you have to include jQuery.cookie.js file in your webpage. After user logged in set its cookie. It will remain set unless you remove it or after specific time. When you restart server all sessions will be destroyed but cookie will remain in browser. So if there is no session but cookie present in browser you can automatically logged in user and create its session again.
$.cookie("test", 1);
To delete:
$.removeCookie("test");
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("test", 1, { expires : 10 });
To read back the value of the cookie:
var cookieValue = $.cookie("test");

Restore previous session's attribute

Suppose, a use login with username="ABC",
Some data is set in the session as follows:
session.setAttribute("mydata", mydata);
If the current session expires, the user is redirected with login page.
And now, if the user again login with same username ("ABC"),
Can we retrieve the previous session's attribute so that the user can continue his work?
Please suggest me the possible solution to retrieve the data of previous session.
Thank you.
I don't believe it is possible . However, you can always create a semaphore where your app can check against it whenever the user logs in and invalidate the session if there's already an existing user session running.
This semaphore could be as simple as a Java static variable if you are running in a non-clustered environment, or a better approach is to set the flag in a database table especially if you are running in the clustered environment.
Not possible, when the session expires everything it contains is dead. This is controlled by the container.
You could save session attributes to database beofre they expire, then add them back to the new session when user logs in again.

Categories

Resources