August 28, 2011

JSP Life-cycle methods

The 3 life-cycle methods of a JSP are,
  • jspInit()
  • _jspService()
  • jspDestroy()
The jspInit() executes when the object of the JSP servlet class is created by the Container, right after the constructor finishes executing.

The jspDestroy() executes when the JSP Servlet object is removed or taken down by the Container.

The _jspService() method executes everytime a request is sent to the JSP. Code in scriptlets and expressions lands in the _jspService() method.

Code in the JSP declaration element lands outside the _jspService() method but inside the JSP Servlet class, after translation.

The jspInit() and jspDestroy() methods execute only once in the life of the JSP Servlet object. The _jspService() executes n times, where n = number of requests sent to the JSP

Create a JSP - JspLifecycleDemo.jsp - in the WebContent folder of the web application,

<title>JSP lifecycle methods</title>
public void jspInit() {
   System.out.println("JSP initialized"); 

public void jspDestroy() {
   System.out.println("JSP Destroyed"); 

<%= "Inside _jspService() method"  %>


Test the code with the following URL in the browser,


Check the server/console log for the output of the jspInit() method. Stopping the server will display the output of the jspDestroy() on the server/console log.

No comments:

Post a Comment