The following code illustrates how to invalidate a session when a browser is closed using Ajax. We have call the unload() function using onbeforeUnload event which calls the sessionInvalidate function which uses AJAX to call the servlet which invalidates the session.
<script language="javaScript">
function unload()
{
sessionInvalidate();
}
</script>
Body part of the JSP
--------------------
<body onbeforeUnload="unload()" >
.....
....
...
</body>
function sessionInvalidate()
{
var url = 'servlet/misc.sessInv'; sessInv is the servlet class
if (window.ActiveXObject)
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
httpRequest = new XMLHttpRequest();
}
httpRequest.open("GET", url, true);
httpRequest.onreadystatechange = function() {processRequest(); } ;
httpRequest.send(null);
}
function processRequest()
{
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
}
else
{
alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
}
}
}
Serverside Code :
---------------
public class sessInv extends HttpServlet{
protected void doGet(HttpServletRequest requestObject, HttpServletResponse responseObject)
throws IOException
{
HttpSession session = requestObject.getSession(true);
if (session!=null)
{
session.invalidate();
}
}
protected void doPost(HttpServletRequest requestObject, HttpServletResponse responseObject)
throws IOException
{
HttpSession session = requestObject.getSession(true);
if (session!=null)
{
session.invalidate();
}
}
}
0 comments:
Post a Comment