Jsp and Servlet Tutorials - Jsp lifecycle - jspInit(), _jspService() & jspDestroy() (Part 5 of 8)
In this particular blog we will learn about complete life cycle of a jsp file and implementation of jsp lifecycle methods. A JSP file goes through a number of states during its execution, here is a brief introduction to those states :
JSP lifecycle is consists of jspInit(), _jspService() and jspDestroy(), and these methods are called life cycle methods of the JSP.
JSP page translation and compilation phase
Every JSP page is first translated to a servlet before going through other lifecycle states. The container than validates the syntax for correctness of jsp components used on the page. The translated servlet file is than compiles into a java class file.JSP class loading and execution.
In execution phase of a compiled jsp file the container maintained the request-response instances occurred during the lifecycle. Jsp consists of three lifecycle methods listed below.1) jspInit() method
2) jspService() method
3) jspDestroy() method
What is jspInit() method
Once a JSP file is successfully compiled into a class file, jsp engine calls jspInit() method to initialize class file. This method is called by the container only once during the lifecycle. jspInit() method can be overridden by the author to initialize resources such as database and network related connections.- public void jspInit() {
- // initialization code or something needs to be called before JSP page
- // starts serving the requests.
- }
What is _jspService() method
_jspService() method is called every time a request comes to jsp during its lifecycle. The (_) underscore sign indicates that this method is generated by Container and hence cannot be overriden. The jsp code written by us goes in _jspService() because this is implicitly implemented. In case we tries to override it explicitly, JSP compliler will give an error saying “the method is already implemented and cannot override’.What is jspDestroy() method()
jspDestroy() method is called when servlet(jsp) is no longer in use, with the call of this method jsp lifecycle is ended and jsp submits itself to garbage collection.- public void jspDestroy() {
- // code related to release resources like database ot network
- // connections.
- }
In this particular blog we came across 'JSP life-cycle methods and their use and implementation', in upcoming blogs we will discuss more about java and other opensource technologies.
Thanks for reading !

0 comments
Post a Comment