Monday, January 28, 2013

What is Java Servlets?


What is Java Servlets?

A Servlet is a Java-based server-side web technology. Technically speaking, a Servlet is a Java class in Java EE that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. Servlets could in principle communicate over any client–server protocol, but they are most often used with the HTTP protocol. Thus "Servlet" is often used as shorthand for "HTTP Servlet". Thus, a software developer may use a servlet to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting.


To deploy and run a Servlet, a web container must be used. A web container (also known as a Servlet container) is essentially the component of a web server that interacts with the Servlets. The web container is responsible for managing the lifecycle of Servlets, mapping an URL to a particular Servlet and ensuring that the URL requester has the correct access rights.
The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the web container and a servlet.


A servlet is an object that receives a request and generates a response based on that request. The basic Servlet package defines Java objects to represent Servlet requests and responses, as well as objects to reflect the Servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the web server and a client. Servlets may be packaged in a WAR file as a web application.


Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. While the direct usage of Servlets to generate HTML (as shown in the example below) has become rare, the higher level MVC web framework in Java EE (JSF) still explicitly uses the Servlet technology for the low level request/response handling via the FacesServlet. A somewhat older usage is to use Servlets in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model–view–controller pattern.


Methods of  Servlet
A Generic servlet contains the following five methods:

init()

public void init(ServletConfig config) throws ServletException
The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. 

Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred.

service()

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and  javax.servlet.ServletResponse are passed by the servlet container.  

The status code of the response always should be set for a servlet that throws or sends an error.

Parameters -  The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception.
 

getServletConfig()

public ServletConfig getServletConfig() 
This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.
Returns -  the ServletConfig object
destroy()

public void destroy() 
This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held. 

  
Life Cycle of Servlet

The life cycle of a servlet can be categorized into four parts:
  1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
  2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

    The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
  3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
  4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet  releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.




Advantages of Servlet

1.  Portability
As we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations.  We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server. So servlets are write once, run anywhere (WORA) program.

2.  Powerful
We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to  request. It can do many other things which are difficult to implement in the CGI programs.

3.  Efficiency
As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. 

4.  Safety
As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to  Java's exception handling mechanism. If any exception occurs then it will throw an exception.

5.  Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets.

6.  Inexpensive
There are number of  free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.





1 comment:

  1. helpful and insightful while being straight forward and to the point. Thanks for the posting.Affordable Web Development

    ReplyDelete