3

If JSP turns into a Servlet why there are different life cycle methods for example jspInit() and init() ?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Harshana
  • 7,297
  • 25
  • 99
  • 173

2 Answers2

3

The reason there is a jspInit separate from the servlet init method is one is there for the servlet implementing the JSP (created by the developer implementing the servlet container), the other is there for the JSP code (used by the application developer). If the JSP used the init method it could override whatever the servlet implementation was doing. With separate methods the JSP implementer can take the code from the jspInit and add it to the init method of the generated servlet.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
2

I'll try to explain it correctly in the most simple way (as addition to the correct @Nathan Hughes answer) :

From the perspective of HTML vs JAVA code, servlet is more like HTML wrapped with JAVA. It gives a strong support for handling application layer in the multilayered architecture. On the other hand JSPs were created to support the creating of presentation layer. The init() method of a servlet is called only once during initialization of the servlet.

So the first point : Servlets were here before JSPs.

Now to JSPs. Again from the perspective of HTML and JAVA, JSP is more like JAVA wrapped with HTML.

WEB CONTAINER performs a translation of the JSP "source code" to the equivalent Servlet java code. This translated java Servlet source code is then compiled and the WEB CONTAINER handles the realisation of the Servlet. Simply:

MyPage.jsp --> (translate) --> MyPage_jsp.java --> (compile) --> MyPage_jsp.class --> (load) --> Java Servlet

The jspInit() method is called by WEB CONTAINER as a part of the initialization phase of the JSP lifecycle.

So to your question : jspInit() not equals init().

Fallup
  • 2,417
  • 19
  • 30