Interview Question in JSP


 

Interview Question :: Explain the life-cycle mehtods in JSP?

 Explain the life-cycle mehtods in JSP?

by ksk
VoteNowAnswers to "Explain the life-cycle mehtods in JSP?"

 THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService(). 

The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
by ksk

The life cycle of the jsp page is given below:

  1. jspInit(): This method is the called form the init() method. This method is of interface javax.servlet.jsp.JspPage. We can override this method. This method will be called once when the container loads the servlet for the first time.
  2. _jspService(): This method is called from the servlet's service method. The container passes the Request and Response objects to this method. We can't override this method. It is a method of javax.servlet.jsp.HttpJspPage interface. 
  3. jspDestroy: This method is called by the servlet's destroy() method. We can override this method. It is a method of javax.servlet.jsp.JspPage interface.

 

As Example The code of the program is given below:

 

<html>
<head>
<title>The lifecycle of jsp page</title>
</head>

<body>
<h1>Showing the life cycle of jsp using jspInit and jspDestroy</h1>
<%!
int num;
int count;
public void jspInit()
{
count++;
num = 10;
}

public void jspDestroy()
{
count--;
num = 0;
}
%>

<%
out.println("The number is " + num + "<br>");
out.println("The counter is " + count + "<br>");
%>
</body>
</html>
by Deepika