Servlet Architecture: Basics of Servlets

A Servlet is a class, which implements the javax.servlet.Servlet interface. However instead of directly implementing the javax.servlet.Servlet interface we extend a class that has implemented the interface like javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.

Servlet Exceution

This is how a servlet execution takes place when client (browser) makes a request to the webserver.

Servlet architecture includes:

a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be implemented directly or indirectly by extending 
GenericServlet or HttpServlet class.

b) Request handling methods
There are 3 methods defined in Servlet interface: 
init(), service() and destroy().

The first time a servlet is invoked, the init method is called. It is called only once during the lifetime of a servlet. So, we can put all your initialization code here.

The Service method is used for handling the client request. As the client request reaches to the container it creates a thread of the servlet object, and request and response object are also created. These request and response object are then passed as parameter to the service method, which then process the client request. The service method in turn calls the doGet or doPost methods (if the user has extended the class from HttpServlet ).

c) Number of instances

Basic Structure of a Servlet

public class firstServlet extends HttpServlet {

   public void init() {

      /* Put your initialization code in this method,

       * as this method is called only once */

   }

   public void service() {

      // Service request for Servlet

   }

   public void destroy() {

      // For taking the servlet out of service, this method is called only once

   }

}