Question

Question on sessions

Asked by: Micheal_Male

say for instance you have the session timeout set for an application to default which is 30 min. You have a page which is written using spring and jstl tags. The jsp page is connected to the controller. In the jsp i am checking one of the session objects to see if it still exist. If yes good if not then send the user back to the index page which is the login page. However it is frustrating sometime because if the form is big then the user has to login back and fill out the form fields.  Is it possible to set the session timeout to one hour for just this one page instead of changing the whole application session ?.

I don't want to refresh the page through a javscript as i will loose all of the form fields. Any input example will be great.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-22 at 17:42:26ID24753546
Tags

spring framework

,

j2ee

,

jsp

,

javascript

Topics

Spring

,

JavaScript

,

Asynchronous Javascript and XML (AJAX)

Participating Experts
2
Points
125
Comments
29

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Over Engineered? Hibernate+SPRING+STRUTS+JSTL
    I understand it's been a while in the market that the combination among SPRING, Hibernate, Sturct, JSTL to come out with a fantastic application. There are lot of user complaining about the combination is over engineered or it's not suitable for the beginner to use as it's v...
  2. jstl in welcome.jsp
    hi guys this peice of code works in my jsp, but i was just curious if i can remove all scriplets and use jstl to make it work. any ideas will be appreciated. =============welcome.jsp========================== <% final String SERVERS = com.aoc.store.utils.PropertiesProx...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: MuraliKanthPosted on 2009-09-22 at 19:24:23ID: 25399582

use the following AJAX code to  alert the user about extending the session.
Ajax will not reload /refresh the whole page and its ideal to use.


//servlet code

session = request.getSession();                       
                StringBuffer xml = new StringBuffer();                
            xml.append("<?xml version=\"1.0\"?>\n");

                   xml.append("<session userid=\"" + (String)session.getAttribute("userId") + "\">\n");
                    xml.append("</session>\n");
           
            response.setContentType("text/xml");
            response.getWriter().write(xml.toString());
            response.getWriter().flush();

/*
 * Returns an new XMLHttpRequest object, or false if the browser
 * doesn't support it
 */
function newXMLHttpRequest()
{
	var xmlreq = false;
 
	// Create XMLHttpRequest object in non-Microsoft browsers
	if (window.XMLHttpRequest)
	{
	  xmlreq = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
	    try
	    {
	      // Try to create XMLHttpRequest in later versions
	      // of Internet Explorer
	
	      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
	    }
	    catch (e1)
	    {
			// Failed to create required ActiveXObject
			try
			{
				// Try version supported by older versions
				// of Internet Explorer
				
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e2)
			{
			  // Unable to create an XMLHttpRequest by any means
			  xmlreq = false;
			}
		}
	}
 
	return xmlreq;
}
 
 
/*
* Returns a function that waits for the specified XMLHttpRequest
* to complete, then passes it XML response to the given handler function.
* req - The XMLHttpRequest whose state is changing
* responseXmlHandler - Function to pass the XML response to
*/
function getReadyStateHandler(req, responseXmlHandler)
{
	// Return an anonymous function that listens to the XMLHttpRequest instance
	return function ()
	{
		// If the request's status is "complete"
		if (req.readyState == 4)
		{
			// Check that we received a successful response from the server
			if (req.status == 200) 
			{
				// Pass the XML payload of the response to the handler function.
				responseXmlHandler(req.responseXML);
			}
			else
			{
				// An HTTP problem has occurred
				alert("HTTP error "+req.status+": "+req.statusText);
			}
		}
	}
}
 
function extendSession(){
  var req = newXMLHttpRequest(); // ajax.js
  req.onreadystatechange = getReadyStateHandler(req, updateSessionInfo);
  req.open("POST", "/servlet/SessionHandler", true);
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  req.send("pageKey=extendSession");
}
 
function updateSessionInfo(sessionXML){
	  var session = sessionXML.getElementsByTagName("session")[0];
	  var userid = session.getAttribute("userid");	   
	  if(userid == 'null' || userid == null){
		  msgToUser();
	  }
}
 
function promptUser(){
  //extensionWanted = false;
  if (confirm('Your login session will expire in 5 minute. Would you like to extend the session?')){
		//extensionWanted = true;
		extendSession();
		setSessionTimeout();
  }
}
 
 
 
function setSessionTimeout(){
      // prompt timeout message 5 mins before timeout
      // it is assume to be 30 mins before timeout
      setTimeout('promptUser()', 25 * 60 * 1000);
      //setTimeout('promptUser()', 1 * 60 * 1000);
      //setTimeout('logout()', 30 * 60 * 1000);
      //setTimeout('promptUser()', 5000);
      //setTimeout('logout()', 10000);
}
 
setSessionTimeout();

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:

Select allOpen in new window

 

by: HainKurtPosted on 2009-09-22 at 19:38:29ID: 25399630

on server set it to 1 hour...

also, put these logic to your all pages...

on session_start
session("session_created") = now

on every page

if session_timeout goto login page
if (page <> my long page) and (now - session("last_activity") >20) logout (or session.abondon) ; go to login page

what we are doing is setting actual server timeout to 1 hour, but programatically we are setting it to 20 min (for all pages but your long page)

 

by: Micheal_MalePosted on 2009-09-22 at 19:55:17ID: 25399696

Murali thanks for the response. I am using DWR AJAX Framework unfortunately i was not able to find any method in the documentation which will keep the session alive. However if i can make your code work then this is exactly what i need. Will update in a few

 

by: Micheal_MalePosted on 2009-09-22 at 19:56:24ID: 25399700

Hainkurt unfortunately there are lots of JSP so to update all the JSP is next to impossible.

 

by: HainKurtPosted on 2009-09-22 at 20:00:43ID: 25399713

what about just inserting a hidden iframe into your long page, which refreshes the tiny page every 10-20 minutes?

<iframe src="refresh.asp" width=0 height=0/>

and refresh.asp is just a dummy page like this:

<html>
<head>
<meta http-equiv="refresh" content="600">
<title>refresh</title>
</head>
<body><body>
</html>

 

by: HainKurtPosted on 2009-09-22 at 20:01:48ID: 25399716

I thought you have a header / footer files, which is included by every page :)

bad design... what about the previous solution?

 

by: HainKurtPosted on 2009-09-22 at 20:04:38ID: 25399720

that page will never expires, but you can create a counter and if it is 6, then you can send

<script>
alert("session ended, you have to start again, sorry");
document.href.src="login.asp";
</script>

or you can implement some other logic...

 

by: Micheal_MalePosted on 2009-09-22 at 20:05:37ID: 25399723

yes. No headers and footers :(. Hmmm i thought about using iframe and refresh it but was afraid if my values are still going to be intact or not. Let me try that.

 

by: MuraliKanthPosted on 2009-09-22 at 20:21:07ID: 25399775

@Micheal_Male

the code i have posted is a working version in one of my projects. You need to just give a hit to server to keep ur session alive.Thats what is achieved with my code.

 

by: Micheal_MalePosted on 2009-09-22 at 20:34:16ID: 25399831

Murali the only issue is that i am using spring framework so i have a controller. However i see in your code you are referencing it to a servlet.

req.open("POST", "/servlet/SessionHandler", true);

I do have a listener class by the name of SessionTracking and over there i implemented HttpSessionListener. In this class i am setting the session time and redirecting it to the login page if there is no session in sessionDestroyed() method.

I don't want to do anything with the login servlet where it sets all the session as it might break something. Just concerned.

 

by: MuraliKanthPosted on 2009-09-22 at 20:42:26ID: 25399859

HttpSessionListener would get triggered for the session creation/destroy  period. Actually if you set session timeout as say 45 mins thn you need to hit the server atleast 5 mins well in advance to reset ur session timeout automatically. For achieving this you need to have a servlet or a controller re-directed to some class where u just return some unique id(userid)  for validating the session.

This cycle of giving a hit to server before 5 mins would reset ur session timeout and there by the HttpSessionListener would not be triggered. You can possibly have a indivdual servlet for this purpose or a seperate controller (my knowledge on Spring Controller is limited).

-Murali*

 

by: Micheal_MalePosted on 2009-09-22 at 21:00:52ID: 25399920

Thanks for your response. Actually i know what an HttpSessionListener will do which i was sure will not achieve the desire result which i am trying to accomplish as you stated in the comment. I am using a MultiActionController and in one of the methods (which is 'Insert' method which inserts the values in the DB) i am already getting the userid from the session. So if the session is not active then a blank page is displayed. However if i write something like this in my jsp :-

<%
session = request.getSession(false);
//now check if the userId is null from the session
//if it is then set the header and redirect the user to the login page
%>

then the user is redirected to the login page. Now if you think this will not work then i think as per you i need to create a seperate servlet which will just have a simple method of getting the useid or validating if the session is still active. And then make it available in web.xml and then use the Ajax code you posted in my long page ? Correct ?

Lastly it looks like the function you posted i will be putting it in my jsp and calling promptuser method in body onload ?

 

by: MuraliKanthPosted on 2009-09-22 at 21:09:25ID: 25399954

Yes you are correct.

Actually u need to place the functions all in a single .js file and include to the page where u need it.
It would automatically call the servelt or controller at( 25 * 60 * 1000) 25th minute (you can change it as necessary).  setSessionTimeout(); would be executed automatically and you need not to call any function explicitly.

 i have a additional function msgToUser(){ }  where u can redirect to a login page if session has already expired.

 

by: Micheal_MalePosted on 2009-09-23 at 18:13:19ID: 25409542

Murali. Thanks. I was able to create a servlet and was able to achieve the desired result. Although i must admit that this is a perfect solution for keeping the session alive for a specific page without changing the session timeout. I had alot of other senarios to consider like get the session Id and then increase the timeout for that session. But your example was much more helpful than anyone else.

I will urge to create a blog if possible because while searching on google i could'nt find any good resource on AJAX implementation of refreshing page. Your blog will definitely help other users out just like. Thanks .

 

by: Micheal_MalePosted on 2009-09-23 at 18:14:12ID: 31632261

With the walkthough murali provided i was able to implement it.

 

by: MuraliKanthPosted on 2009-09-23 at 18:15:58ID: 25409552

Thanks for your suggestions. I would  definitely update my existing blog @scribblejava.wordpress.com.

 

by: Micheal_MalePosted on 2009-10-04 at 12:30:23ID: 25490439

Hi Murali. I have a question on this senario which you posted. Say for instance a user clicks OK to confirm for the session. For how long the session will be extended ?. It looks like it does not extend for 30 more minutes. It extends for 5 or 10 minutes. Thanks

 

by: Micheal_MalePosted on 2009-10-04 at 13:19:04ID: 25490722

For some reason when i do an alert in aler(userid) i get undefinied. Could you tell me why ?. It makes the call to the servlet and i can get the userid from the log statement but when i try to print on the JS function in sessionextend i get undefined for the userid.

Can you tell me what i am doing wrong murali ?

 

by: Micheal_MalePosted on 2009-10-04 at 17:31:53ID: 25491660

I found what the problem was.So when i press ok for the pop up message to extend the session before 5 min of expiring apparently it is suppose to ping my servlet and should refresh the session correct ?. However after clicking ok if i stay idle on the same page for a little 10 more min and click submit on the form i get a null pointer in my controller. In my controller i am getting the userid from session and It states that the userId which i am getting from the session is null ? could you tell me why is it doing that ?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String user = (String)request.getSession(false).getAttribute("user");
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\"?>\n");
		xml.append("<session userid=\"" + user + "\">\n");
 
		xml.append("</session>\n");
		response.setContentType("text/xml");
		response.getWriter().write(xml.toString());
		response.getWriter().flush();
	}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

 

by: MuraliKanthPosted on 2009-10-04 at 18:44:55ID: 25491899

Hi Michael,

So when i press ok for the pop up message to extend the session before 5 min of expiring apparently it is suppose to ping my servlet and should refresh the session correct ?

>> Yes you are correct. But remember u cannot leave the alert for 5+ mins and then click on the "OK" to make the session extension. Because from the time it shows the alert it counts. So if you click on "OK" immediately after seeing the alert it should extend the session.  By extension we mean the session-timeout reset.


could you tell me why is it doing that ?
>> could you make sure your session is still active before u get the userid from session in ur controller?.






 

by: Micheal_MalePosted on 2009-10-04 at 18:55:18ID: 25492049

Thank you Murali for your comments. So i clicked Ok before 5 min of my session expiring. And then i stay idle for 10 min and then when i click submit on my form my onBindAndValidate() method gets invoked. In that method i am getting the userId and couple of other stuff from the session. I added some log statements and then came to know that i receive a null pointer exception on :-

String user = (String)request.getSession(false).getAttribute("user");
log.info("user is " + user );

I get a null pointer on :-

String user = (String)request.getSession(false).getAttribute("user");

meaning that the session is not alive. What could be the problem ?. I can see that the PingSession servlet does get call when i click ok but session never gets extended.

 

by: Micheal_MalePosted on 2009-10-04 at 18:58:43ID: 25492059

I am sure i told you before that we don't have a session-timeout. however we do have a SessonListener which is set to default 30 min. I don't think that the listener is either a problem also.

 

by: MuraliKanthPosted on 2009-10-04 at 19:01:45ID: 25492068

Make sure the setTimeOut() has the timer value exactly 5 mins before session timeout.
Also ignore using false in getSession().

String user = (String)request.getSession().getAttribute("user");

Could you also add log statement to OnsessionDestroyed in your session listener, to check when ur session is destroyed?.

 

by: Micheal_MalePosted on 2009-10-04 at 19:24:27ID: 25492132

I don't think request.getSession(false) will make any difference. However i did put some logger statements in my listener on timing when the session is created and destroyed. Now i saw it created a session 2 min earlier and now monitoring to see when it will be destroyed. I will check in 30 min with that ajax implementation function also to see if my session gets expired earlier or not.

in setMaxInterval of listener i setted to 1800 which means 30 min. Will update in 30 min

 

by: MuraliKanthPosted on 2009-10-04 at 19:35:04ID: 25492159

You should set the timer to 25 mins and not 30 min. So every 25mins once it triggers the session extension.

 

by: Micheal_MalePosted on 2009-10-04 at 19:56:52ID: 25492221

I am sorry i did'nt get you murali ? In my JS i have set the timeout to :-

//25 min for prompt
setTimeout('promptUser()', 25 * 60 * 1000);

Now when i click ok in the pop up message i saw my servlet get called PingSession. I printed the userid and the XML does have the userId. But after 5 min of clicking OK in the pop up message i saw the log printed that the session is destroyed also. Why the session got destroyed in the listener when i did ping the servlet through the AJAX function also ?

 

by: MuraliKanthPosted on 2009-10-04 at 21:02:49ID: 25492406

It looks really wierd. Did you try just by letting the application be idle for <30 mins and before it reaches 30 mins to click on somelink and see if it still expires the session. I would recommend you to set the session timeout in web.xml to 30 mins and then try this out.

 

by: Micheal_MalePosted on 2009-10-04 at 21:09:17ID: 25492421

hmm sounds like a good idea of setting the session timeout in web.xml. I will let you know. BTW thanks for your help murali. I will keep you updated. If you want i can create a seperate thread to give you some points in debugging with me.

 

by: MuraliKanthPosted on 2009-10-04 at 21:29:40ID: 25492468

I would be glad to help you in debugging this problem. Its up to you to create a seperate thread.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...