Friday, November 4, 2011

Understanding JSP Life Cycle

JSP never outputs the content directly to the browser. Instead, JSP relies on initial server-side processing process which translates JSP page into the JSP Page class. The page class then will handle all the requests made of JSP. The JSP life cycle is described as the picture below:
JSP Life Cycle
JSP Life Cycle
JSP life cycle can be divided into four phases: Translation, Initialization, execution and finalization.

Translation

In the translation phase, JSP engine checks for the JSP syntax and translate JSP page into its page implementation class if the syntax is correct. This class is actually a standard Java servlet. After that, JSP engine compiles the source file into class file and ready for use.
If the container receives the request, it checks for the changes of the JSP page since it was last translated. If no changes was made, It just loads the servlet otherwise the process of check, translate and compile occurs 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, JSP engine loads the class file and create an instance of of the servlet to handle processing of the initial request. JSP engines will call a method jspInit() to initialize the a servlet. jspInit method is generated during the translation phase which is normally used for initializing application-level parameters and resources. You can also overide this method by using declaration.
<%!
   public void jspInit(){
      // put your custom code here  
   }
%>

Execution

After the initialization phase, the web container calls the method _jspService() to handle the request and returning a response to the client. Each request is handled is a separated 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 the 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 the jspDestroy() method also to do your all clean up such as release the resources you loaded in the initialization phase....
<%!
   public void jspDestroy(){
      // put your custom code here 
      // to clean up resources
   }
%>

No comments:

Post a Comment