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);
}
}
}
}
// to ensure on page load, the session is still active
window.onload=function(){
validateAndExtendSession();
}
window.onunload=function(){} // fix for Firefox when browser back button is clicked
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
validateAndExtendSession();
});
</script>
function validateAndExtendSession(){
var req = newXMLHttpRequest();
req.onreadystatechange = getReadyStateHandler(req, updateSessionInfo);
req.open("GET", "/servlet/SessionHandler", true); //modify to point to ur servlet
req.send(""); //use POST when queryparameters are used
}
function updateSessionInfo(sessionXML){
var session = sessionXML.getElementsByTagName("session")[0];
var userid = session.getAttribute("userid");
if(userid == 'null' || userid == null){
msgToUser();
}
}
function msgToUser(){
alert("Session already expired. Please re-login to the application");
//redirect to login page since the session has already expired and no more extension possible
}
function promptUser(){
if (confirm('Your login session will expire in 5 minute.Would you like to extend the session?')){
validateAndExtendSession();
}
}
function setSessionTimeout(){
// prompt timeout message 5 mins before timeout
// it is assumed to be 30 mins before timeout
setTimeout('promptUser()', 25 * 60 * 1000);
}
//default call to the timer function
setSessionTimeout();
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();
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)