Saturday, May 21, 2011

Java Servlets

Servlet is a Java class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request(like HTTP, FTP), they are commonly used to extend the applications hosted by Web servers.


Servlets runs at Server side typically Web Server or Application server, and respond to request by giving the response to user after processing the request. 


A servlet that implements SingleThreadModel means that for every request, a single servlet instance is created. This implementation helps in implementing the business applications like bank transactions. 


A multi-threaded servlet means that one servlet is capable of handling many requests which is the way most servlets should be implemented. This allows servlets to support systems such as on-line conferencing.


A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets.


As Servlet are written in java, they can make use of extensive power of the JAVA API,such as networking and URL access, multithreading, databaseconnectivity, RMI object serialization.

A Servlet implementation can be done in three ways:

  1. By implementing the Sevlet interface into your class. The class which implementing the Servlet interface, should implement all the servlet life cycle methods defined in the Servlet interface.
  2. By writing a subclass to GenricServlet present in the javax.servlet package. The subclass must override the abstract service method present in the Generic servlet class.
  3. By writing a subclass to HttpServlet present in javax.servlet.http package. The subclass of HttpServlet must override any of the methods in doGet(), doPost(), doDelete(), doPut(), init(), destroy(), getServletInfo().


In general most of the cases Servlet implementation can done by sub classing to GenericServlet or HttpServlet.
Below are the differences between HttpServlet and GenericServlet:
  1. HttpServlet is the subclass of GenericServlet.
  2. Generic Servlet defines a generic, protocol-independent servlet. HttpServlet provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site.
  3. A sub class which extends GenericServlet must implement the abstract service() method. A subclass of HttpServlet must override at least one method, usually one of these: doGet(), doPost(), doDelete(), doPut(), init(), destroy(), getServletInfo().

Click here to know Servlet Life cycles

2 comments:

Divya said...

Very helpful blog... thanks for sharing....

Gunda said...

Thanks Divya