Question

Session issue

Asked by: Micheal_Male

I got a solution from one of the expert and was able to implement it also. What i want to do is keep the session alive for long forms. However, i can see that the JS function does hit my servlet but unfortunately the session still gets destroyed after default 30 min time instead of being extended. I do have a HttpSessionListener class which is set to default 30 min.

I added some log statements to see when the session is created and destroyed and it gets destroyed after 30 min. However when it reached 29 min i tried going to another page and everything works great.

import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class PingSession
 */
public class PingSession extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
    public PingSession() {
        super();
    }
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doPost(request, response);
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\"?>\n");
		xml.append("<session userid=\"" + (String)request.getSession().getAttribute("users") + "\">\n");
		xml.append("</session>\n");
		System.out.println(xml.toString());
		response.setContentType("text/xml");
		response.getWriter().write(xml.toString());
		response.getWriter().flush();
	}
 
}
*******************************
JS Function
******************************
 
 
 
function newXMLHttpRequest()
{
        var xmlreq = false;
 
        
        if (window.XMLHttpRequest)
        {
          xmlreq = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            try
            {
              
        
              xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e1)
            {
                       
                        try
                        {
                               
                                
                                xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e2)
                        {
                         
                          xmlreq = false;
                        }
                }
        }
 
        return xmlreq;
}
 
 
 
function getReadyStateHandler(req, responseXmlHandler)
{
        
        return function ()
        {
                
                if (req.readyState == 4)
                {
                        
                        if (req.status == 200) 
                        {
                                
                                responseXmlHandler(req.responseXML);
                        }
                        else
                        {
                                
                                alert("HTTP error "+req.status+": "+req.statusText);
                        }
                }
        }
}
 
function extendSession(){
  var req = newXMLHttpRequest(); 
  req.onreadystatechange = getReadyStateHandler(req, updateSessionInfo);
  req.open("POST", "/servlet/PingSession", 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(){
  if (confirm('Your login session will expire in 5 minute. Extend the session?')){
                extendSession();
                setSessionTimeout();
  }
}
 
 
 
function setSessionTimeout(){
      setTimeout('promptUser()', 25 * 60 * 1000);
}
 
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:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:

Select allOpen in new window

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-10-05 at 17:47:42ID24787495
Tags

spring framework

,

j2ee

,

ajax

,

jsp

,

servlet

Topics

Java Servlets

,

J2EE

,

Asynchronous Javascript and XML (AJAX)

Participating Experts
1
Points
500
Comments
22

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. Destroying Sessions and Setting Expiration times on Sessions
    I am hoping that someone can help me with this. What i want to do is Destroy my session when a user leaves a certain area. I have a logout function that if people use works fine but the problem is not everyone clicks the logout link to log themselves out. Another question ...
  2. session Destroy
    Hi I have an application using php sessions, but when i try to logout the program and destroy sessions it does' not work this is my exit code <?php session_start(); session_unregister('first_name'); session_unregister('user_level'); $_SESSION=array(); s...
  3. Session not destroying?
    I pretty much just self tought my self PHP today (going from ASP). I have a simeple log in page, an authentication page, then the protected pages. When the user closes the web browser, the session should expire in 24 minutes if i am correct (in php.ini, session.gc_maxlife)....

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-10-05 at 18:35:54ID: 25501274

Hi Micheal,

Could you please post your HttpSessionListener class code. Just i wanted to give it a try on my machine.

-Murali*

 

by: Micheal_MalePosted on 2009-10-05 at 18:44:53ID: 25501314

Here it is.

import login.LoginController;
 
import java.sql.Timestamp;
 
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
 
public class HttpSessionController implements HttpSessionListener{
 
	
	public void sessionCreated(HttpSessionEvent argument1) {
		System.out.println("Timestamp " + new Timestamp(System.currentTimeMillis()));
		argument1.getSession().setMaxInactiveInterval(1800);
		
	}
 
	public void sessionDestroyed(HttpSessionEvent argument2) {
		System.out.println("Timestamp destroyed " + new Timestamp(System.currentTimeMillis()));
		LoginController.logUserOut(argument2);
	}
 
	
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: MuraliKanthPosted on 2009-10-05 at 18:50:05ID: 25501341

request.getSession().setMaxInactiveInterval(1800);

-- add the above line to the PingSession Servlet  doPost method. Since u have set the session timeout programatically it doesn't extend the session on hit to servlet.

try this.

-Murali*

 

by: MuraliKanthPosted on 2009-10-05 at 18:54:39ID: 25501374

Also there are differences between <session-timeout> setting in web.xml and using setMaxInterval().

A session which has setMaxInterval() would automatically get expired after the time specified, whereas for those session that doesn't have setMaxInterval() it looks for default <session-timeout> application setting in web.xml and based on that it expires.

I hope in your case since setMaxInterval() is set it doesn't have an idea of what value to reset the session.
Alternatively u can remove the setMaxInterval() from ur HttpSessionListener & ur Pingsession servlet(if u added that setMaxInterval()) and configure it in web.xml and then give it a try then it should work like a gem.

-Murali*

 

by: Micheal_MalePosted on 2009-10-05 at 19:10:04ID: 25501434

Great information Murali. That is why when i added sesison-timeout it had no effect because the Listener was still getting invoked. I have added the maxInterval time in my PingSession also. Hopefully this will resolve the issue. I will update in a little bit.

 

by: Micheal_MalePosted on 2009-10-05 at 20:57:54ID: 25501793

I tried adding setMaxInterval in my Ping Servlet but unfortunately the result is the same. It does not extend the session. I don't know what the main reason is. I am trying one more trick to see if that will help. if not then i will remove the listener from web.xml and will configure the session-timeout in web.xml which will be set to 30 min and then i will see if that will work or not. Thanks for your help. I will update later on.

 

by: Micheal_MalePosted on 2009-10-05 at 21:46:59ID: 25501961

I removed the listener and added this in web.xml :-

<session-config>
<session-timeout>30</session-timeout>
</session-config>

Hope this works.

 

by: Micheal_MalePosted on 2009-10-05 at 22:36:35ID: 25502088

Same thing murali. With session-timeout or without session-timeout.

 

by: MuraliKanthPosted on 2009-10-05 at 23:04:14ID: 25502173

that stumped me all together. Fine, are you using Spring WebMVC and its controller  for ur page request?
If yes can u try pointing the .js to the controller and handle the session handling code there instead of a seperate servlet?

since u already have a parameter pageKey=extendSession, you can add the following (if) in the controller and then copy the rest of the session extending code.

if("extendSession".equalsIgnoreCase(request.getParameter("pageKey"))){
//create xml and flush it.
}

I have the same set of code , running on a Tomcat server and its working perfectly. What server do you use?.

-Murali*

 

by: Micheal_MalePosted on 2009-10-06 at 18:42:18ID: 25511544

I used Sun one web server. In the meantime i read about XMLHttprequest and the JS function is working properly. Session will always be renewed when you hit a server doPost() method. however, In my case who knows what might be wrong and why it is not renewing the session.

Our login page is a servlet where as the page which is long is a controller. I am still trying to see why
<session-config>
<session-timeout>30</sessio-timeout>
</session-config>
is not working.

 

by: MuraliKanthPosted on 2009-10-06 at 18:47:40ID: 25511578

<session-timeout>30</sessio-timeout> -- is it a typo on ur web.xml or on post.

I m trying to figure out what might have gone wrong..will let u know

 

by: Micheal_MalePosted on 2009-10-06 at 19:00:05ID: 25511647

Thanks for your help murali. Yes that is a typo. I read AJAX On java book and the book offers some examples in how to send request to the server asynchronously through XMlHttpRequest. It's pretty much the same thing you posted.

 

by: MuraliKanthPosted on 2009-10-08 at 00:11:07ID: 25522826

@Micheal:

Any luck?.  I just gone through different sites but couldnt find something useful for this issue.
Just a wierd one was check if u use acegi.jar (try replacing with the latest one).

I would suggest a workaround for this problem,

Instead of servlet (PingSession) you pass the control to one of the Spring Controllers (dummy) probably which is empty and doesn't do anything (dont  frwd to any target page).

Give it a try...

-Murali*

 

by: Micheal_MalePosted on 2009-10-08 at 17:19:07ID: 25531533

Just curious murali. So now as i understand you i will create a simple controller using spring framework. I can probably use handlerequestInternal method of the controller to do exactly what i was doing in PingSession servlet. I will do :-

String param = request.getParameter("pageKey");
If pageKey is extendSession then
do all the XML stuff what i did in my servlet.

My only question is that what do i need to do over here ? :-

req.onreadystatechange = getReadyStateHandler(req, updateSessionInfo);
  req.open("POST", "/servlet/PingSession", true);

As the controller is suppose to be defined in applicationContext if you want to make it available in the application. Thank you for all your help man in solving this wiered issue. I can't find anything in the code itself to see why is it not extending the session :(

 

by: Micheal_MalePosted on 2009-10-08 at 17:19:44ID: 25531535

And yea we are not using any acegi security in our application.

 

by: MuraliKanthPosted on 2009-10-09 at 04:50:35ID: 25533999

 req.open("POST", "/servlet/PingSession", true);
>> you need to change the servlet call to your spring controller call. Just like how you do it in ur jsp page.
I don't have any code samples as of now, just give a try.

 

by: Micheal_MalePosted on 2009-10-12 at 20:41:05ID: 25556793

I tried to use the same controller. When i added this :-

req.open("POST","/jsp/addUser.jsp",true);

I get an error stating :-

"Neither bindingresult nor command object user is available as request". I know this is the most common error in spring but how can i get rid of it ?. I put the xml code in refrenceData as refrenceData is always called when a page refreshes as per spring documentation. I think my problem is the frames.

 

by: Micheal_MalePosted on 2009-10-13 at 17:38:23ID: 25566206

hmm . Creating a Controller in spring and then calling the JSP and resetting the session time in the controller through AJax have done the trick for me :).
I can stay on the same page as long as i want to now :--). However, i have only one question murali.  This function :-

function updateSessionInfo(sessionXML){
          var session = sessionXML.getElementsByTagName("session")[0];
          var userid = session.getAttribute("userid");    
          if(userid == 'null' || userid == null){
                  msgToUser();
          }
}

When i try to put alert statement i get 'null or no object' in this method. I putted aler(session) and i got null over there also. The code does send the request to my controller but since it is a MVC and i am using just a simpleformcontroller i don't know what to return ?

return new ModelAndView(getSuccessView());

I believe this is my problem that is why i am not getting anything in the response in AJAX. Any tips ?

 

by: MuraliKanthPosted on 2009-10-13 at 18:31:59ID: 25566433

Glad that you are successful in making an AJAX call.

Actually you need not to return anything from the controller unless u need to show an alert to the user.
So i just browsed few items and got this for how to return an xml from Spring Controller. See if it helps,

http://www.extjs.com/forum/showthread.php?t=61891

http://forum.springsource.org/showthread.php?t=28323

-Murali*

 

by: Micheal_MalePosted on 2009-10-13 at 19:13:01ID: 25566735

Let me see if i can make it work.

 

by: Micheal_MalePosted on 2009-10-13 at 19:19:34ID: 25566760

Hmm. Well that is true also i do'nt want to show anything to the user in the alert statement except for just that pop up message. However if i just leave it like the way it is everything works fine also but i get a Javascript error. I am trying to see what can i remove from the ajax code so that the JS error is not shown to the user in the task bar,

 

by: Micheal_MalePosted on 2009-10-16 at 19:38:25ID: 31637498

Thanks for your help murali. I am still stuckon this problem and i plan to do more research later on and will try to find an appropriate solution. If i keep hitting the serer after every 5 min everything works fine if the server stays idle for more than 10 min then no matter what i do the session gets destroyed. I will add comments in this post if i need any input from you. Thanks for all your help man. BTW i like your blog and have started supporting it. You are a great helper and very knowledged guy.

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