Advantages of using Servlets:
- Performance is improved significantly. Reason being that Servlets execute within the address space of a web server. It is not necessary to create a separate process to handle each client request.
- Java is used to write Servlets. So they are platform-independent. The Java security manager on the server enforces a set of restrictions to protect the resources on a server machine.
- The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms.
Lifecycle of a Servlet
Steps that explains the life cycle of
Servlet:
- Invoked only when the servlet is first loaded into memory. Loads the resources in this step.
- Invoked for every HTTP Request. Reads data from HTTP Request and formulates the HTTP Response.
- Invoked when server decide to unload the servlet. Releases memory and objects allocated to Servlet.
Steps that explains the life cycle of Servlet:
- A Using browser a user tries to access a web site, then browser generates an HTTP Request.
- HTTP Request reaches web server and Server will load the relevant servlet dynamically to address space.
- Now the init() method of servlet will be invoked by Server to initialize it. Server also passes initialization parameters to servlet.
- service() method of servlet is called to process the HTTP request. Its read the data from Request and forms the HTTP Response. Servlets remains in address space of server to process any other request from client. service() method is called for each HTTP Request.
- The server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected.