Introduction to Java Servlet

Posted at September 8, 2016 at 6:20 pm by Jithin

What is Servlet?

A Servlet can be simply defined as a program that extends the capabilities of a server. Usually the Servlet is in java and can respond to web requests. The Servlets implement applications hosted on web servers. In such cases, these Servlets are the counterpart to other technologies used to implement dynamic web contents such as ASP.NET and PHP.

 

Introduction to JAVA

Java is a programming language and computing platform. It was first released by the Sun Microsystems in 1995. Java is one of the integral parts of the web industry that many websites rely on.  Java is a general purpose high-level programming language which is class-based and an object-oriented programming language.

 

 A Detailed Overview

Servlets are commonly used to process or store a  Java class in Java EE. It will conform the Java Servlet API. It is a standard for implementing Java classes which respond to the requests. Even though Servlets can communicate over every Client-Server protocol, it is often used with the HTTP protocol. The Servlet is a way  to add dynamic web content to a web server using the Java platform. In addition they can use HTTP cookies and maintain the state in session.

 

What is Servlet container?

To deploy and run a Servlet, we need to use a web container. A web container is an essential component of a web server that interacts with the Servlets.  It is usually referred to as a servlet container. The web container is used to manage the life cycle of the Servlets and they are responsible for mapping a URL to a particular Servlet. It ensures that the URL requester has the correct access rights. The java package hierarchy javax.servlet contains the Servlet API. It defines all the expected interactions of the web container and the Servlet.

Servlets can be generated automatically from Java Server Pages (JSP). The difference between the Servlet and the JSP is Servlet usually embed the HTML inside the Java code. The JSPs embed the Java code in HTML. The Servlet was created by the Sun Microsystems with version 1.0 released and was finalized in 1997. As of June 9, 2015, the current version of the Servlet is 3.1. Let’s see the different versions of Servlets and the major updates done in each versions

Servlet API versions and major changes done

Servlet API version Released in Major Changes
Servlet 4.0 Under developement HTTP/2
Servlet 3.1 2013 Non-blocking I/O, HTTP protocol upgrade mechanism (Web Socket)
Servlet 3.0 2009 Pluggability, Ease of development, Async Servlet, Security, File Uploading
Servlet 2.5 2005 Requires Java SE 5, supports annotation
Servlet 2.4 2003 web.xml uses XML Schema
Servlet 2.3 2001 Addition of Filter
Servlet 2.2 1999 Becomes part of J2EE, introduced independent web applications in .war files
Servlet 2.1 1998 First official specification, added RequestDispatcher, ServletContext
Servlet 2.0  1998 Part of Java Servlet Development Kit 2.0
Servlet 1.0 1997

 

 

Life Cycle of a Servlet

There are three methods which are central to the Servlets. They are init(), service() and destroy().

At the time of initialization of Servlet, the web container initializes the Servlet instances by calling the init() method. It will pass an object and implement the javax.servlet.ServletConfig interface. This is a configuration object and it will allow the Servlet to access the name-value initialization parameters from the web application.

Now, when the initialization is completed, the Servlet can service the client requests. The requests are serviced in threads. In the case of multiple requests, each request is serviced in its own separate thread. Here, the service() method is the one being called by the web container. This method needs to be called for every requests. The service() method request determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the Servlet must provide an implementation for these methods. If a request is made for a method that is not implemented by the Servlet, the method of its parent class is called and usually it will return an error to the requester.

In the final step, the web container calls the destroy() method that takes the Servlet out of service. This is the overview of a Servlet.

Both the init() and destroy() methods are called only once in the lifecycle of a Servlet. Let’s see an example for this.

1) A user requests to visit a URL

The browser then generates an HTTP request for this URL and the request is sent to the server.

2) The HTTP request is received by the web server and forwarded to the Servlet container.

The container maps this request to a particular Servlet and then the Servlet is dynamically retrieved. It is loaded to the address space of the container.

3) The container invokes the init() method of the Servlet.

The init() method will be invoked only once in a Servlet’s life cycle. If we pass initialization parameters, it will configure itself.

4) In the next step, the container will invoke the service() method of the Servlet.

The purpose of this method is to process the HTTP requests. The Servlet may read the data that has been provided in the HTTP request and it may also formulate an HTTP response for the client.

5) The Servlet remains in the containers address space and it can process any other HTTP requests received from the clients. For every request, the service() method is called.

6) At some point, the container could decide to unload the Servlet from its memory. This decision will be taking according to different conditions for each container.

7) The destroy() method Servlet’s is called by the container will relinquish any resources and important data may be saved to a persistent store. The memory allocated to the Servlet and its objects are  garbage collected.

 

Example

The given below is an example Servlet which prints how many times its service() method was called.

import java.io.IOException;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 public class ServletLifeCycleExample extends HttpServlet {

 private int count;

@Override

    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        getServletContext().log(“init() called”);

        count = 0;

    }

    @Override

    protected void service(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        getServletContext().log(“service() called”);

        count++;

        response.getWriter().write(“Incrementing the count: count = ” + count);

    }

    @Override

    public void destroy() {

        getServletContext().log(“destroy() called”);

    }

}

 

If you need any further assistance please contact our support department.

 

 

0.00 avg. rating (0% score) - 0 votes

You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply