What is the lifecycle of a JSP page? Please include details of the internal mechanisms of JSP engine.

Scott Stanchfield

First, the internal workings of the JSP engines can vary between servers. There is a general lifecycle that applies to all servers, but a few implementation differences may exist.

That said, the lifecycle of JSPs is actually pretty simple:

  1. A user makes an HTTP request (usually a GET or POST) to the server
  2. If the request matches a registered pattern, the server calls the JSP page compilation servlet. Note that this registered pattern can usually be changed. Most often it's "*.jsp", but you could create other patterns or restrict the page compilation to certain directories on the server.
  3. The Page Compilation servelet checks if the page actually exists. If not, it returns a 404 (not found) error
  4. The Page Compilation servlet checks to see if it needs to regenerate/recompile the page. This determination is usually based on some server settings. In general, if a certain "timeout" setting has passed since the page was last accessed, it checks to see if the page source is newer than the last-generated servlet for it. If so, we need to regenerate.
  5. If we need to regenerate the servlet for the JSP, the Page Compilation servlet translates the JSP code to Java servlet source. Then the Page Compilation servlet compiles the generated servlet. Compilation errors result in an error page being sent to the user.
  6. If the servlet isn't currently loaded in the server (or has changed), the server loads it and calls its init() method, passing a ServletConfig object to describe the server and pass initialization parameters.
  7. The server calls the servlet's service() method, passing an HttpServletRequest and HttpServletResponse. The generated servlet calls the code contained within the JSP, passing these parameters as request and response.
  8. The server returns the resulting stream of (usually HTML) to the browser that asked for it.

Finally, if the server decides to discard the generated servlet (usually when noone has requested it for longer than a preset timeout period), it calls the servlet's destroy() method, then drops the reference to that servlet (making it a candidate for garbage collection.)

Keep in mind that JSPs are nothing but servlets in nicer clothing. They can do the exact same things as a servlet, but are generally easier to write.