Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

How JSP Functions ? Lifecycle of JSP .

Java Server Page (JSP) is a serverside program that is similar in design and functionality to JAVA Servlet . JSP program consists of a compination of HTML tags and JSP tags. JSP tags define Java code that is executed before the output of the JSP progam is sent to the browser.

How JSP functions or Lifecycle of JSP?
When a client requests a jsp , First time JSPs are converted into servlets and then compiled before they get executed. The code inside the JSP gets placed into the converted servlets service() method.

JSP has three methods which is automatically called when a JSP is requested.

1. jspInt() 2. jspDestroy() 3. sevice()

1. jspInt() : similar to init() method of a Servlet :- when a JSP is requested , jspInt() is called first.

2. jspDestroy() : similar to destroy() method of a servlet :- automatically called when a JSP terminates. can be used to cleanup the resources used during the execution (eg. disconnecting from database )

3. service() : similar to service() method :- automatically called and makes HTTP connection.
Read more...

Session invalidate when browser closed using ajax

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();
}

}
}
Read more...

 
Copyright 2011 Java Online