Sunday, June 18, 2017

GenericServlet

To implement the Servlet interface, one needs to provide classes for all methods specified in the interface, even if the method is not used by the servlet.  To simplify coding, GenericServlet is an abstract class that implemented the Servlet inteface. GenericServlet supplies implementation for the method in the interface so that the real servlet class only needs to override those method it uses.

GenericServlet also saves the ServletConfig object passed by the servlet container to the init method in a persistent variable so the real servlet can access it later on.  GenericServlet adds another init method with no argument for the real servlet to override with its specific code.

GeneicServlet is implemented as abstract class as it expects the real servlet implementation override one of more methods before it is used.

Servlet Interface

The Servlet interface specified s contract between the servlet container and the servlet.  Servlet container calls the init method of the servlet one time during start up.  When a request comes in, servlet engine calls the service method of the servlet to process it.

Servlet engine will also pass in a ServletConfig object to the servlet application's init method.  ServletConfig contains initialization parameters. ServletConfig also provide a SrvletContext object. The ServleCcontext contains global data accessible by all classes in the servlet. In a distributed environment, each servlet instance can access the same ServletContext data.

Servlet also defines two objects - ServletRequest and ServletResponse that used by service method.  ServletRequest defines methods to retrieve parameters submitted in a request.  For example, "id" is the parameter which the method returns as string value.

http:::.../servlet?id=1

ServletResponse simplifies the returning of response to the client. It defines methods to let the application to write the response to a certain stream and let servlet container to handle the rest.

To implement a serlvet, one create a class implement the Servlet interface or extend a class that implemented the Servlet interface.