How JSPs Become Servlets
The underlying implementation of JSPs is Servlets, so why use one over the other? JSPs have a big advantage over Servlets because JSPs offer the separation of roles. The Web artists can create the aesthetic feature of the Web page and the Java programmer can add the dynamic content. Also, the programmers do not need to be sophisticated Java programmers and be aware of creating classes and inheritance like they would when writing Servlets. You may be concerned that the performance of your application will decrease if you use JSPs since they get translated, but you will see why this is not always true. Now take a look at the lifecycle of JSPs/Servlets and also the translation between JSPs and Servlets.
The JSP/Servlet Lifecycle
Since the underlying implementation of JSPs is via Servlets, the lifecycle of both are the same. Figure 3.1 shows the lifecycle of a JSP/Servlet.
Figure 3.1 The lifecycle of JSPS/servelets is pretty straightforward.
You start with a JSP or a Servlet class. The server is responsible for instantiating the JSP/Servlet and it uses the new() method to accomplish this. This new() method is the Java method for creating space in memory for an object.
After the JSP/Servlet is instantiated, the init(...) method is invoked for initialization purposes. The init(...) method will be looked at in more detail in a few minutes.
Then the JSP/Servlet moves into the Ready state and is prepared to handle client requests. You can write a service(...) method to handle your business logic or you can write a doGet(...) or doPost(...) method for your business logic. These methods will be discussed shortly.
The JSP/Servlet is then destroyed when the server invokes the destroy() method (container invoked). The garbage collector finally comes around and cleans up the memory with the finalize() method.
The JSP Translation Process
The JSP is translated into the appropriate Servlet code, which is a .java file. Many application servers provide the option of keeping the generated .java files. Once it is translated into the .java file it is compiled into the bytecode file (.class). The .class file is executed and the output HTML document is generated and sent back to the client. Figure 3.2 shows a diagram of this process.
Figure 3.2 Follow the JSP through its translation process: it does its real work halfway through.
Now you may think that this is a large process and that the performance will take a large hit. Well, after the first invocation of a JSP, subsequent requests will not go through the translation phase but will go to the already compiled .class file. Many application servers allow you to dictate how long an application server should wait before it checks if your JSP has changed and needs to be recompiled. Many application servers also provide a compiler for JSPs so the first hit on the JSP will not notice a performance decrease.