Will session gets timed out when request taking time to load - java

In web.xml I've mentioned 5mins as the session time out.
Suppose if my request to load page with data from db taked morethan 5 mins what will happen.
Will the request get processed ? will the sessiong timeout get extended?

The session is attached with a timestamp generate on the server. This timestamp is used by the server to know if the session is timeout.
So when you'll access the session in this process or an other, if the timer is ended, the session will be out of date even if it is caused by a too long processing of the last request.

It will expire, as there is no communication happening between client and server. On the other hand, for these kind of long-running jobs, it is better to use some sort of async/batch technology, and let the client check results later.

Related

Cassandra - Set write timeout with Java API

I am trying to set the write timeout in Cassandra with the Java drive. SocketOptions allows me to set a read and connect timeout but not a write timeout.
Does anyone knows the way to do this without changing the cassandra.yaml?
thanks
Altober
The name is misleading, but SocketOptions.getReadTimeoutMillis() applies to all requests from the driver to cassandra. You can think of it as a client-level timeout. If a response hasn't been returned by a cassandra node in that period of time an OperationTimeoutException will be raised and another node will be tried. Refer to the javadoc link above for more nuanced information about when the exception is raised to the client. Generally, you will want this timeout to be greater than your timeouts in cassandra.yaml, which is why 12 seconds is the default.
If you want to effectively manage timeouts at the client level, you can control this on a per query basis by using executeAsync along with a timed get on the ResultSetFuture to give up on the request after a period of time, i.e.:
ResultSet result = session.executeAsync("your query").get(300, TimeUnit.MILLISECONDS);
This will throw a TimeoutException if the request hasn't been completed in 300 ms.

How do I renew a spring session?

I have a web application running spring MVC on Websphere, and I am trying to implement a session expiration confirm. I now where to redirect if they choose to log out but I don't know how to renew a session if the choose to do that.
So far I understand I am using jQuery and ajax to send a request somewhere to the server but do not know where (the url), nor the arguments or the expected response. Does anyone know have a general idea how I find this out? Is it a standard function of spring session or am I going to have to write a custom function to fix this?
I was able to figure it out by combining information from multiple sources out on there. I came up with the following code:
function timeoutMessage(){
var popupdate = new Date();
var renewSession = confirm('Your Session is about to expire!\n\nYou will be logged out in 2 minute.\nDo you want to stay signed in?');
if(renewSession){
var response = new Date();
if(response - popupdate > 120000){
alert("Response took too long, current session has ended. \nRedirecting to login.");
}else{
pingServer();
resetTimeout();
}
}else{
window.location.href = "{app logout url}";
}
}
function pingServer(){
jQuery.ajax({url: "{valid server page url}",type: "HEAD",complete: function (XMLHttpRequest, textStatus) {}});
}
function resetTimeout(){
window.setTimeout(function(){timeoutMessage();},1080000);
}
$(document).ready(function()
resetTimeout();
});
The function sets a timer that coincides with two minutes before the session timeout. Most sites will offer most of the above code but what that in the pingServer() function; in order to extend the session on the server you can send a simple ajax call of type 'HEAD' to the server without interrupting the applications primary flow. It is seen as an action by the server toward the session and thus resets/renews the session's timeout. You don't need to do anything with the server response as seen in the code; just as long as you send the request the session timeout will be reset/renewed.
I hope this helps. It took me a while to completely piece together.
Why not set a bigger number for max_inactive_interval so the session will last longer?
Spring Session automatically renews if the user is active. Take a look at the table created by Spring Session for storing the session data: there is a column max_inactive_interval which basically means that the session will only expire if the user is not active for that interval of time.

How to prevent data loss when user session expired?

I have a web app, which session expired in 30 minutes. At client side, when the user tries to interact with server and server detects user session is expired, the client will simply redirects to log in page.
The problem is, user may not know his session is expired, and keep working on client side(say, writing a note, or edit something), when he tries to send the changes to server, bad thing occurs, the browser redirects to log in page and user data is lost.
Any idea on how to prevent data loss when user session expired? Thanks.
If the user is writing a note or editing anything on his session the session should not expire.
You can easily send a keep-alive message to the server for every 5th (or even more) character he presses keeping the session alive.
Have you considered raising the session timeout? 30 minutes is pretty low. It might take some users longer than that to fill in one Web form, even if they are working continuously. My session timeouts are 8-10 hours. The only reason to make them shorter is to save space at the server. Is that a problem that you really have?
You will need to provide some sort of support in the server. A good implementation would be a servlet called every 31 minutes of user "iddleness" (to avoid revalidating session which would cause it to never expire) from the client via an AJAX call.
If the session id changes in the server it would reply so and the client could show some sort of message.
An easier implementation would be firing some kind of reload every 31 minutes of inactivity, so that the user is redirected to the login page. That wouldn't need any extra support in the server, but would be less user-friendly.
There are reasons to have short session time out.
Security
Data Theft
If you don't need those, just extend the session time out.
OR,
Insert AJAX calls every where to renew the session.
In the HTML you can have an alert after 29 minutes (JS setTimeout), and after 30min - 10s (meta refresh) do a jump to a "session expired" page.
Session only expire if user will not done any action till 30 minutes.
If user did not do anything till 30 mins, then there should not be any data lost by idel session expired coz there is nothing to retain.
Please don't forget to add {{ csrf_field() }} in your form.
I had the same problem. Then, I put crsf token here! And, it works fine now. Here is my code:
<form method="post" action="{{route('customer.store')}}" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row">
//Your code here
</div>
</form

How to create one database connection per user on a Java Servlet application?

I am working on a website using Java Servlets and my research showed me that it is best to keep one database connection per user (rather than have only one connection sitting all the time on the background or connect to the database every time that a transaction needs to be made). I don't know how to accomplish this, however. What I am currently doing is in my Data Access Object class I have a
private static Connection conn;
and I have a HTTPSessionListener - on sessionCreated event I connect to the Database using this static "conn" variable, and on sessionDestroyed event I disconnect the "conn" variable:
...in my "MySessionListener"...
public void sessionCreated(HttpSessionEvent sessionEvent) {
System.out.println("Session created!");
DAO.connect();
}
public void sessionDestroyed(HttpSessionEvent sessionEvent)
{
System.out.println("Session destroyed");
String user = (String) sessionEvent.getSession().getAttribute("userid" );
if (user != null) DAO.signUserOut(user);
DAO.disconnect();
}
Now the problem with this is that:
I am afraid that this way I essentially degrade to only having one connection that everyone shares(instead of a connection per user as I wanted), just that I disconnect from time to time if there are no users. Correct?
If multiple users are online and one closes their session, they will close the connection for everyone until someone else starts a session and creates a new connection for everyone, correct? I cannot test this very well because I am testing it locally on my laptop, with 3 browsers, but even when I close a browser that had my website on, the session doesn't die immediately and I am not sure what exactly is going on. All i know is that sometimes I get an exception saying "No transactions allowed after connection is closed".
Typically this is achieved using connection pool. You can configure it to have specific number of connections available and the pool manages open and closing connections. Your code will only take available connection from the pool and return it when done.
See this (fairly generic) Wikipedia article.
Some well known pools are DBCP and C3P0.
There ate two issues here:
http session timeout
database session connectivity
You seem to be mixing the two session concepts.
HTTP session
You need to further familiarize yourself with client-server http mechanism. Closing the browser does not close the http session. When you close the browser, you have to code into your pages "on close". "On close"?? Absolutely not - there is no such thing as onclose in html/javascript. But there is onunload (as well as onload).
Why isn't there "onclose" in javascript/html? I think the people who invented http/html were paranoid over many contingencies. Perhaps, rightly so. Perhaps, we have to understand the mindset and motivation of html/http invention. So, you have no choice but concoct a chain-reaction of onunload events. ONUNLOAD/ONLOAD are html page events, not browser events. The whole html mechanism is page driven not browser driven. Therefore, when you close the browser, it would trigger onunload event for every tab on the browser.
You will have to make use of page onunload to inform the server that the user has intention to close the session. Otherwise, the server would have to depend on session timeout value to end the session. What if the user closes the browser on one of your pages on which you did not code in the onunload event? Too bad - that is why I wrote "concoct a chain reaction of onunload" on every page. Which is very tiresome and bothersome.
Sometimes. especially for highly mathematical servlets, the server takes a long time to respond. Then the client page would need an indication to differentiate between a server still processing a response vs the server has gone dead - session timeout enforced on the browser. e.g. http://support.microsoft.com/kb/813827 (How to change the default keep-alive time-out value in Internet Explorer).
May be, the server should poke at the browser page once a while to see if the browser session is still alive. Nope. Http is client pull technology. The server cannot push responses to the client. Why not? Why so silly? You have to read up on the whole http/html mindset/paranoia to understand. The browser can poke at the server but not vice versa.
Therefore AJAX and comet was invented/concocted. To simulate, to pretend on server push. With ajax you have some means for the server to psuedo-poke at the client. And that is what you have to do -- use ajax e.g. jquery or gwt. I prefer gwt.
What if the client computer had a power failure or the OS hit a blue screen, or the browser process was abruptly terminated? There would be no opportunity to trigger the onunload event for any of the pages.
Database connection session
Alex's answer hit the nail -- connection pooling. However, there are situations when I needed to have a database connection per session. Hmmm ... how do I do it? Yes, I store the connection as the session attribute. Therefore, there would be as many db connections as there are sessions. Which, essentially has the same effect as what you are currently doing.
Developing stateful web applications for a stateless(despite the cookies) and presumed unstable client requires cautiousness. What if the user presses the back button after logging out? The backed/prev page might contain an action that causes the server to use a db connection, which was already closed by the log-out page before the user pressed the back button. Or, it may be the server timed out due to client not having poked at the server for a duration longer than the session keep-alive timeout value.
Therefore, before developing a "multi-tier" client-server app, you have to sit down and chart out all your contingencies, with a good understanding of the mindset/paranoia of http technology. You need to infect yourself with http's compulsive obsessions in order to design your applications.

tracking Httpsession user session timeout

I am trying to monitor user session and alert user that the session is about to expire.
Anysolution either client side or server side will work for me , i just need to inform to the client that his session would be expired before session expires
Session timeout counter starts as soon as it gets idle. if there is a request from user [even if its ajax] then it won't time out. So you can maintain a counter on client side making sure that user is left idle for your webpage.
Update:
Add a Filter that will intercept each request and will update lastAccessedTime pass it to client in the form of some hidden parameter or cookies or something.. and use javascript to detect the timeout
Also See
detecting-idle-time-in-javascript-elegantly
The timeout should definitely be handled using a Javascript type of timer. Now, when you have a request on the server you should reset the timeout on client (the session timeout on the server will be automatically updated using the session tracking option of the server).
Now in another case that you perform actions on the client (but with no server interaction) then you should reset the timeout on the client using javascript, and use a dummy hidden internal frame posting some dummy form on a dummy page on the server. This would update the session timeout of the user on the server side.
You can also implement the last dummy thing functionality also with an ajax call on a dummy page. This might be a better solution.
Hope this helps you

Categories

Resources