Engineering Full Stack Apps with Java and JavaScript
JSPs are actually servlets. Container will convert all jsp files as servlets before executing it. By default, the JSP is compiled into a servlet and then loaded the first time it is accessed. This might cause a small delay for the first request, but there won’t be any delay in subsequent requests. You may also precompile JSPs before adding them into JARs. Certain application servers might even provide tools for doing so.
The non-java lines like html, comments, javascript, css etc. are called as template text. There will be print statements for each of these non java lines in the converted servlet.
JSP to Servlet conversion also makes the life of container easy as it needs to know to execute only servlets, which are pure java classes.
Even though JSPs are eventually converts as servlets, you cannot override the servlet life cycle methods from a JSP.
Servlets are generated from JSPS during JSP translation phase of the JSP life cycle.
The generated servlet has some special characteristics like below:
The servlet (or one of its superclasses) must implement the javax.servlet.jsp.HttpJspPage interface, or
For the tiny minority of non-HTTP, specialist JSP containers, the servlet (or one of its superclasses) must implement the javax.servlet.jsp.JspPage interface.
A container vendor will typically have a specialized JSP base servlet, extending and implementing all required classes or interfaces.
In Tomcat, this is called org.apache.jasper.runtime.HttpJspBase. HttpJspBase extends HttpServlet and GenericServlet, and implements javax.servlet.jsp.HttpJspPage, javax.servlet.jsp.JspPage, java.io.Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig.
This generated servlet also has additional methods specific to JSPs which are related to the JSP life cycle.
In Tomcat, the generated servlet's Java source and compiled class, by default, is kept @ <Tomcat-Installation-Directory>/work/Catalina/localhost/<context-directory>/org/apache/jsp. For instance if your url is http://localhost:8080/JSP-Demo/simplejsp.jsp, you can find the source and class of the servlet @ <Tomcat-Installation-Directory>/work/Catalina/localhost/JSP-Demo/org/apache/jsp.