As we saw in earlier chapters that JSP is translated to Servlets and generated Servlet class that implements certain interfaces. In this chapter we will look at those interfaces and complete hierarchy along with the related APIs.
4.2 JSP API
The main package of JSP API is javax.servlet.jsp which contains all the interfaces.
The base interface of JSP API is javax.servlet.jsp.JspPage and has a child interface javax.servlet.jsp.HttpJspPage which extends JspPage interface.
Container generates Servlet class from a jsp file that implements HttpJspPage interface
4.2.1 JspPage Interface
This is the main interface and defines two jsp lifecycle methods
a) jspInit() – This is the lifecycle method and executes only once in the lifecycle of a jsp page. 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. This method is called from init method of Servlet.
We can override jspInit() method and add custom initialization code in it.
b) jspDestroy() - 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
This method is called from destroy() method of Servlet and we can override this method to add custom clean up code.
4.2.2 HttpJspPage Interface
HttpJspPage interface extends JspPage interface and defines one life cycle method.
a) _jspService(HttpServletRequest, HttpServletResponse) – This lifecycle method executes upon a new request for a Jsp page. This method is called from service() method of servlet which means this method is executed in a separate thread. Container passes Request and Response object in this method
This method is added by default in the generated servlet class which means we cannot override this method and doing so will result in an error.
All the code written inside a scriplet tag ( <% %> ) or any html code goes inside this method
Generated Servlet class implements HttpJspPage interface which means all three ( jspInit() , jspDestroy() and _jspService() ) methods are available in the class.
Tips: You must have observed that _jspService() method has a “ _ ” pre-pended with the method name where as this is not the case with other two methods. You can remember it like it is a sign that Specification warns you not to touch.