What exactly happens behind the scenes when a JSP page is compiled? Is it converted to a servlet? If it is, then does each request to a JSP page result in the creation of a new servlet?

Ashish Bhatia

The first time a request is made for a JSP file, either directly from a client browser or from a servlet, the JSP file is translated into a servlet by the "JSP engine" (which is itself a servlet -in the JSWDK, it is known as JspServlet). If there are any syntax errors within the JSP file, the translation phase fails, triggering an error message to the client.

If it was successful, the generated servlet code is compiled, the servlet is loaded into memory by the JSP engine. At this point, the JSP engine also invokes the jspInit() method, and initializes the servlet. The jspInit() method is invoked just once during the lifetime of the servlet. Then the jspService() method is invoked to process the request and reply to the client. For all subsequent requests to the JSP page, the server checks to see whether the .jsp file has changed since it was last accessed. If there is no change, the request is handled by the jspService() method of the servlet stored in memory in a concurrent manner. Note that since the servlet is always stored in memory, the response is very fast.

If the .jsp file has changed, the server automatically recompiles the page file, replaces the servlet in memory, and handles the request as described above.

Although JSPs are efficient, there is a slight delay on the first request for a .jsp page since the JSP file has to be compiled into a servlet. Also, the JSP engine may remove the servlet from memory in a non-deterministic way at any time owing to resource constraints. When this happpens, it first invokes the jspDestroy() method, before flagging the servlet instance for garbage collection.