Introduction of Servlet in JAVA

Introduction

 
The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. Initially, Common Gateway Interface (CGI) scripts were the main technology used to generate dynamic content. Although widely used, CGI scripting technology has a number of shortcomings, including platform dependence and lack of scalability. To address these limitations, Java Servlet technology was created as a portable way to provide dynamic, user-oriented content. Server-side java solves the problems that Applets are when the code is being executed on the server-side there are no issues with browser compatibility or long download time.
 

What is a Servlet?

 
Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client-side) to answer client requests. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP. Servlet programming is first created by Sun Microsystems in June 1997. The latest version is Servlet 2.5 which is released with JEE 5.0 specification.
 
In other words, Java Servlet is the server-side Java programming language, acting as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Their job is to:
  1. Read any data sent by the user.
  2. Lookup any other information about the request that is embedded in the HTTP request.
  3. Generate the results.
  4. Format the results inside a document.
  5. Set the appropriate HTTP response parameters.
  6. Send the document back to the client.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing Servlets. All Servlets must implement the Servlet interface, which defines life cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
 
The Advantages of Servlets Over "Traditional" CGI
  1. Efficient
  2. Convenient
  3. Powerful
  4. Portable
  5. Secure
  6. Inexpensive

Life Cycle of Servlet

 
The life cycle of a Servlet can be categorized into four parts:
 
Life Cycle of Servlet 
  1. Loaded and Instantiated - The loading and instantiation can occur when the container is started, or delayed until the container determines the Servlet is needed to service a request. when the Servlet engine is started, the Servlet container loads the Servlet class using normal Java class loading facilities. The loading of the Servlet depends on the attribute <load-on-startup> of web.xml file. After loading the Servlet class, the container instantiates it for use for client request.
      
  2. Initialization - After the Instantiated load, the container must be initialized before it can handle the request to the client. The container initializes the Servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. The initialization parameters persist until the Servlet is destroyed. The init() method is called only once throughout the life cycle of the Servlet. The error should occur while the Servlet is initialized which is:
      
    Error Conditions on Initialization.
     
    Tool Considerations.
     
    The Servlet will be available for service if it is loaded successfully otherwise, the Servlet container unloads the Servlet.
     
  3. Servicing the request  or Request Handling - When a Servlet is properly initialized, the servlet container may use to handle a client request which is represented by request object ServletRequest. The ServletResponse() method is to provide the Servlet fill out the response of all the request. While in case of HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends a response to the client using the methods of the response object.
     
    Note some issue occurs by which a Servlet container may handle no requests during its lifetime like:-
      
    Multithreading Issues.
     
    Exceptions During Request Handling.
     
    Thread Safety Issues
     
  4. Destroying the Servlet: The Servlet container is not required to keep a Servlet loaded for any particular period of time. whenever the Servlet container determines that a Servlet should be removed from service then it calls the destroy method of the Servlet interface to allow the Servlet to release all the resources that are held and save any persistent state. The destroy method only call when it must complete execution of any thread that is currently running in the service method of the servlet, or exceed a server-defined time limit. The destroy() method, like init(), is called only once in the lifecycle of a Servlet. 
Life cycle methods
 
The following are the life cycle methods of a Servlet instance:
  1. public void init(ServletConfig config) throws ServletException
     
    This method is called once for a Servlet instance. When the first-time Servlet is called, Servlet container creates an instance of that Servlet and loaded into the memory.
     
    The init method has a ServletConfig parameter. The Servlet can read its initialization arguments through the ServletConfig object. How the initialization arguments are set is Servlet engine dependent but they are usually defined in a configuration file(web.xml).
     
    An example of an initialization argument is a database identifier. A Servlet can read this argument from the ServletConfig at initialization and then use it later to open a connection to the database during the processing of a request 
    1. private String dbURL;  
    2. public void init(ServletConfig config) throws ServletException {  
    3.     super.init(config);  
    4.     dbURL = config.getInitParameter("database");  
    5. }
  2. public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     
    This method is called to process a request. It can be called zero, one or many times until the Servlet is unloaded. This is the entry point for the every Servlet request and here we have to write our business logic or any other processes. This method takes HttpServletRequest and HttpServletresponse as the parameters. It is not mandatory to write this method, normally developers are interested in writing doGet() or doPost() methods which is by default called from the service() method. If you override service(), it is your responsibility to call the appropriate methods. If you are not overridden the service() method, based on the types of request the methods will be called.
    1. import java.io.*;  
    2. import javax.servlet.*;  
    3. import javax.servlet.http.*;  
    4. public class SerLifeCycle extends HttpServlet   
    5. {  
    6.       int count=0;  
    7.       protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
    8.         {  
    9.             response.setContentType("text/html");  
    10.             PrintWriter pw=response.getWriter();  
    11.             count++;  
    12.             pw.println("<html><body>");  
    13.             pw.println("Since loading, this servlet has been accessed " + count + " times.");  
    14.             pw.println("</body></html>");  
    15.        }  
    16. }  
    The variable count is shared by all the threads each corresponding to a single request. So this provides a way for the threads to communicate with each other.
     
  3. public void destroy()
          
    This method is called once just before the Servlet is unloaded and taken out of service. It is used for releasing any resources used by the Servlet instance. Most of the times it could be database connections, Fill IO operations, etc. destroy()  is called by the container when it is removing the instance from the servlet container. Servlet instance is deleted or garbage collected by the container only when the web server issues shut down or the instance is not used for a long time.
    1. public void destroy()  
    2. {  
    3. }
Usage
  • Process or store data that was submitted from an HTML form.
  • Provide dynamic content such as the results of a database query.


Similar Articles