What is the lifecycle of a JSP page? Please include details of the internal mechanisms of JSP engine.
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:
- A user makes an HTTP request (usually a GET or POST) to the server
- 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.
- The Page Compilation servelet checks if the page actually exists. If not, it returns a 404 (not found) error
- 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.
- 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.
- 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.
- 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.
- The server returns the resulting stream of (usually HTML) to the browser that asked for it.
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.