Lifecycle of JSP
A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with one additional first step, which is, translation of JSP code to Servlet code. Following are the JSP Lifecycle steps:
- Translation of JSP to Servlet code.
- Compilation of Servlet to bytecode.
- Loading Servlet class.
- Creating servlet instance.
- Initialization by calling
jspInit()
method - Request Processing by calling
_jspService()
method - Destroying by calling
jspDestroy()
method
Web Container translates JSP code into a servlet class source(.java) file, then compiles that into a java servlet class. In the third step, the servlet class bytecode is loaded using classloader. The Container then creates an instance of that servlet class.
The initialized servlet can now service request. For each request the Web Container call the _jspService() method. When the Container removes the servlet instance from service, it calls the jspDestroy() method to perform any required clean up.
What happens to a JSP when it is translated into Servlet
Let's see what really happens to JSP code when it is translated into Servlet. The code written inside
<% %>
is JSP code.<html> <head> <title>My First JSP Page</title> </head> <% int count = 0; %> <body> Page Count is: <% out.println(++count); %> </body> </html>
The above JSP page(hello.jsp) becomes this Servlet
public class hello_jsp extends HttpServlet { public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { PrintWriter out = response.getWriter(); response.setContenType("text/html"); out.write("<html><body>"); int count=0; out.write("Page count is:"); out.print(++count); out.write("</body></html>"); } }
This is just to explain, what happens internally. As a JSP developer, you do not have to worry about how a JSP page is converted to a Servlet, as it is done automatically by the web container.