Understanding JSP Life Cycle

JSP never outputs the content directly to the browser. Instead, JSP relies on an initial server-side processing process which translates the JSP page into the JSP Page class. The Page class then will handle all the requests made by JSP. The JSP life cycle is described in the picture below:

JSP Life Cycle

JSP life cycle can be divided into four phases: Translation, Initialization, execution, and finalization.

Translation

In the translation phase, the JSP engine checks for the JSP syntax and translates the JSP page into its page implementation class if the syntax is correct. This class is a standard Java servlet. After that, the JSP engine compiles the source file into a class file that is ready to use.

If the container receives the request, it checks for the changes to the JSP page since it was last translated. If no changes were made, It just loads the servlet otherwise the process of the check, translates and compiles takes place again. Because the compilation process takes time so JSP engine wants to minimize it to increase the performance of the page processing.

Initialization

After the translation phase, the JSP engine loads the class file and creates an instance of the servlet to handle the processing of the initial request. JSP engines will call a method jspInit() to initialize the servlet. The jspInit() method is generated during the translation phase which is normally used for initializing application-level parameters and resources. You can also override this method by using a declaration.

<%!
   public void jspInit(){
      // put your custom code here  
   }
%>Code language: JavaScript (javascript)

Execution

After the initialization phase, the web container calls the method _jspService() to handle the request and return a response to the client. Each request is handled is a separate thread. Be noted that all the scriptlets and expressions end up inside this method. The JSP directives and declaration are applied to the entire page so they are outside of this method.

Finalization

In the finalization phase, the web container calls the method jspDestroy(). This method is used to clean up memory and resources. Like jspInit() method, you can override thejspDestroy() method also to do your clean up such as releasing the resources you loaded in the initialization phase.

<%!
   public void jspDestroy(){
      // put your custom code here 
      // to clean up resources
   }
%>