Feb 10, 2010

Advantages of SERVLET

Advantages:
The advantages of using servlets is their fast performance and ease of use combined with more power over traditional CGI. Traditional CGI scripts written in Perl or C have a number of disadvantages when it comes to performance. When a HTTP request is made a new process is created for each call of the CGI script. This overhead of process creation can be very system intensive especially when the script does relatively fast operations (process creation will take more time than CGI script execution). Java servlets solve this problem by allowing each request to be handled by a separate Java thread within the Web server process, omitting separate process forking by the HTTP daemon. In addition, simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as there are requests. However with servlets there are same amount of threads as request but there will only be one copy of the servlet class created in memory.
Lifecycle of a servlet:
The servlet lifecycle consists of the following steps:
The servlet class is loaded by the container during start-up.
The container calls the init() method. This method initializes the servlet and must be called before the servlet can service any requests. In the entire life of a servlet, the init() method is called only once.
After initialization, the servlet can service client requests. Each request is serviced in its own separate thread. The container calls the service() method of the servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester.
Finally, the container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet.
Here is a simple servlet that just generates HTML. Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface. The service() method dispatches requests to methods doGet(), doPost(), doPut(), doDelete(), etc., according to the HTTP request.

No comments:

Post a Comment