05 - JSP Page Life Cycle: Page 2 of 3

5.2.4 JSP initialization

Container calls jspInit() method to initialize the servlet instance before serving any request. This method is called only once for a servlet and is usually used for one time activity like initializing database connections etc.

You need to override and add custom code in jspInit() method (Shown below)

public void jspInit()
// custom initialization code

Below figure shows that Initialization activity is performed by calling jspInit() method


5.2.5 JSP Execution

For each client request of a jsp , container executes _jspService() method passing request and response object.

public void _jspService(HttpServletRequest request,  HttpServletResponse response)
   //  Custom code

This method gets added automatically by container and all the code written inside scriplets , expressions tag goes inside the _jspService() method at the time of translation. Since this method is added by container, you cannot override it in JSP and doing so will result in an error because we cannot have two methods of same name and signature in same java class.

Below figure shows container executes by calling _jspService() method in a separate thread and response is sent to the client.

5.2.6 JSP Clean up

When container removes the corresponding servlet instance , it calls jspDestroy() method to perform any clean up activity.

This method is executed only once in entire life cycle of a servlet (jsp) and you can override it to do clean up activities like closing database connections or any opened files etc

 public void jspDestroy()
   // custom clean up code

Below figure shows container destroys by calling jspDestroy() method to clean up activity.

NOTE: jspInit() and jspDestroy() methods are optional to override because container provides default functionality but you cannot override _jspServcie() method because container by default adds this method.

In above diagram you can see a separation in phases by dotted line (red) to separate the life cycle methods .

Refer below diagram to summarize the life cycle phases we discussed above

Methods / Phases shown in blue colour are life cycle phase methods

Like us on Facebook