Table of contents
1.
Introduction
2.
javax.servlet Package
3.
Classes available in javax.servlet package
4.
Interfaces available in javax.servlet package
5.
Exceptions in javax.servlet package
6.
Classes available in javax.servlet.http package
7.
Interfaces available in javax.servlet.http package
8.
GenericServlet Class
9.
HttpServlet Class
10.
Servlet API Package Hierarchy
11.
Frequently Asked Questions
11.1.
What's the difference between GenericServlet & HttpServlet?
11.2.
What's the purpose of the ServletConfig & ServletContext interfaces?
11.3.
What's a servlet container & what does it do?
12.
Conclusion
Last Updated: Jul 29, 2024
Easy

Java Servlet API

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java Servlet API is a powerful tool for creating web applications. It lets you build dynamic web pages that can interact with users & databases. Servlets are Java classes that handle requests from web browsers & generate responses. They run on a web server & form the backbone of many web apps.

Java Servlet API

In this article, we'll learn about the key components of the Java Servlet API & see how to use them to build robust web applications.

javax.servlet Package

The javax.servlet package contains the core classes & interfaces for building servlets. The most important class in this package is the Servlet interface, which all servlets must implement. It defines methods like init(), service(), & destroy() that control the lifecycle of a servlet.

Here are some of the key classes in javax.servlet:

  • ServletConfig: Provides configuration info about a servlet
     
  • ServletContext: Gives access to app-wide resources & attributes
     
  • ServletRequest: Encapsulates an HTTP request from a client
     
  • ServletResponse: Encapsulates the servlet's response to a request
     
  • GenericServlet: A convenient abstract class to extend when creating a servlet


Let's look at a simple example of a servlet that extends GenericServlet:

import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
    public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello, world!</h1>");  
        out.println("</body>");
        out.println("</html>");
    }
}


This servlet overrides the service() method to generate a simple HTML response when a request comes in. The ServletRequest & ServletResponse objects provide access to the incoming request & the outgoing response.

Classes available in javax.servlet package

The javax.servlet package provides several key classes that you'll use frequently when building servlets. Here are some of the most important ones:

  • ServletConfig: This class provides configuration info about a servlet, like initialization parameters & the servlet name. You can access it from inside a servlet using the getServletConfig() method.

  • ServletContext: This class gives servlets access to app-wide resources & attributes. Multiple servlets in the same app can share data through the ServletContext. You can access it using the getServletContext() method.  
     
  • GenericServlet: This is an abstract class that provides a default implementation of the Servlet interface. It's a convenient base class to extend when creating a new servlet. 


Let's see an example of using the ServletConfig & ServletContext classes:

import java.io.*;
import javax.servlet.*;
public class MyServlet extends GenericServlet {
    public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {
        ServletConfig config = getServletConfig();
        String myParam = config.getInitParameter("myParam");
        
        ServletContext context = getServletContext();
        context.setAttribute("globalData", new String("Hello!"));
        
        // Generate response...
    }
}


In this example, the servlet retrieves an initialization parameter named "myParam" from its ServletConfig. It also stores a string attribute named "globalData" in the ServletContext, which other servlets can access.

Interfaces available in javax.servlet package

The javax.servlet package defines several important interfaces that servlets & web containers rely on. Here are the most essential ones:

  • Servlet: This is the central interface that all servlets must implement. It declares the init(), service(), & destroy() methods that define a servlet's lifecycle.
     
  • ServletRequest: This interface represents an HTTP request from a client to a servlet. It provides methods to access the request parameters, attributes, & input stream.
     
  • ServletResponse: This interface represents a servlet's response to a client. It provides methods to set the response content type, get the output stream, & more.
     
  • SingleThreadModel: This is a marker interface that servlets can implement to indicate they should be run in a single thread per request. However, it's deprecated in later versions of the Servlet API.
     

Let's look at an example servlet that implements the Servlet interface directly:

import java.io.*;
import javax.servlet.*;
public class MyServlet implements Servlet {
    public void init(ServletConfig config) throws ServletException {
        // Initialization code...
    }    
    public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {
        // Handle request & generate response...
    }    
    public void destroy() {
        // Cleanup code...
    }
    
    // Other methods...
}


In most cases, you'll extend the GenericServlet or HttpServlet class instead of implementing Servlet directly, as those classes provide convenient default implementations of the Servlet methods.

Exceptions in javax.servlet package

The javax.servlet package defines a few exceptions that can be thrown by servlets or web containers. Here are the most common ones:

  • ServletException: This is a general exception that a servlet can throw when it encounters difficulty. It's often used as a wrapper for other exceptions that occur within a servlet.

  • UnavailableException: This exception indicates that a servlet is temporarily or permanently unavailable. A servlet can throw this exception from its init() method to signal that it can't be put into service.
     

Let's see an example of throwing a ServletException:

import java.io.*;
import javax.servlet.*;
public class MyServlet extends GenericServlet {
    public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {
        try {
            // Some code that may throw an exception...
        } catch (SomeException e) {
            throw new ServletException("Something went wrong", e);
        }
    }
}


In this example, if the code inside the try block throws an exception, the catch block wraps it in a ServletException & rethrows it. The original exception is passed as the cause to the ServletException constructor.

Servlets can also throw an UnavailableException from their init() method to indicate they can't be initialized successfully:

import java.io.*;
import javax.servlet.*;
public class MyServlet extends GenericServlet {
    public void init() throws ServletException {
        if (someCondition) {
            throw new UnavailableException("Can't initialize servlet");
        }
    }
    
    // Other methods...
}


Here, if someCondition is true, the servlet throws an UnavailableException to signal it can't be put into service.

Classes available in javax.servlet.http package

The javax.servlet.http package contains classes specific to HTTP servlets. These classes build on the basic Servlet API to provide HTTP-specific functionality. Here are some of the key classes:

  • HttpServlet: This abstract class extends GenericServlet & provides a framework for handling HTTP requests. It defines methods like doGet(), doPost(), doPut(), & doDelete() to handle specific HTTP methods.
     
  • HttpServletRequest: This interface extends ServletRequest & provides HTTP-specific methods for accessing request info like headers, cookies, & session data.
     
  • HttpServletResponse: This interface extends ServletResponse & provides HTTP-specific methods for constructing a response, like setting headers & the response status code.
     
  • Cookie: This class represents an HTTP cookie, which is a small piece of data stored on the client & sent back with each request.
     
  • HttpSession: This interface represents a session between a client & a server, allowing data to be stored across multiple requests.
     

Let's see an example of an HTTP servlet that handles GET & POST requests:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // Handle GET request...
        response.setContentType("text/plain");
        response.getWriter().println("Hello from GET!");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // Handle POST request...
        String name = request.getParameter("name");
        response.setContentType("text/plain");
        response.getWriter().println("Hello, " + name + "!");
    }
}


This servlet extends HttpServlet & overrides the doGet() & doPost() methods to handle GET & POST requests separately. It uses the HttpServletRequest to get request parameters & the HttpServletResponse to set the response content type & write the response body.

Interfaces available in javax.servlet.http package

The javax.servlet.http package also provides several interfaces that extend the core Servlet interfaces to provide HTTP-specific functionality. Here are the most important ones:

  • HttpServletRequest: This interface extends ServletRequest & adds methods specific to HTTP requests, such as getMethod() to get the HTTP method (GET, POST, etc.), getHeader() to get request headers, & getSession() to get the current session.
     
  • HttpServletResponse: This interface extends ServletResponse & adds methods for sending HTTP responses, like setStatus() to set the HTTP status code, addCookie() to add a cookie to the response, & sendRedirect() to send a redirect response.
     
  • HttpSession: This interface represents a session between a client & a server. It allows data to be stored across multiple requests from the same client. You can access the current session from an HttpServletRequest using the getSession() method.
     

Let's see an example of using HttpSession to store data across requests:

 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer count = (Integer) session.getAttribute("count");
        if (count == null) {
            count = 1;
        } else {
            count++;
        }
        session.setAttribute("count", count);        
        response.setContentType("text/plain");
        response.getWriter().println("This is visit #" + count);
    }
}


In this example, the servlet uses the getSession() method to get the current HttpSession. It then retrieves a "count" attribute from the session, incrementing it if it exists or initializing it to 1 if it doesn't. Finally, it stores the updated count back in the session & includes it in the response.

This allows the servlet to keep track of how many times a particular client has visited, persisting the count across multiple requests.

GenericServlet Class

The GenericServlet class is an abstract class in the javax.servlet package that provides a basic implementation of the Servlet interface. It's designed to be extended by servlet classes that need to handle protocols other than HTTP.

Here are some of the key methods provided by GenericServlet:

  • init(ServletConfig config): This method is called by the servlet container to initialize the servlet. It takes a ServletConfig object as a parameter, which contains configuration information for the servlet.
     
  • service(ServletRequest req, ServletResponse res): This is the main method that servlets must implement to handle requests. It's called by the servlet container when a request comes in. GenericServlet's implementation of this method does nothing, so subclasses must override it to provide their own request-handling logic.
     
  • destroy(): This method is called by the servlet container when the servlet is being taken out of service. It gives the servlet a chance to clean up any resources it has allocated.
     
  • getServletConfig(): This method returns the ServletConfig object that was passed to the servlet's init() method.
  •  
  • getServletInfo(): This method returns a string containing information about the servlet, such as its author, version, & copyright.
     

Let's see an example of a servlet that extends GenericServlet:

import java.io.*;
import javax.servlet.*;
public class MyServlet extends GenericServlet {
    public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("This is a generic servlet!");
    }
}


This servlet extends GenericServlet & overrides the service() method to provide its own request handling logic. In this case, it simply sets the response content type to "text/plain" & writes a simple message to the response output stream.

HttpServlet Class

The HttpServlet class is an abstract class in the javax.servlet.http package that provides a framework for handling HTTP requests. It extends the GenericServlet class & adds methods specific to HTTP.

Here are some of the key methods provided by HttpServlet:

  • doGet(HttpServletRequest req, HttpServletResponse resp): This method is called by the servlet container when an HTTP GET request is received. It's intended to handle requests that retrieve data from the server.
     
  • doPost(HttpServletRequest req, HttpServletResponse resp): This method is called when an HTTP POST request is received. It's intended to handle requests that submit data to the server for processing.
     
  • doPut(HttpServletRequest req, HttpServletResponse resp): This method is called when an HTTP PUT request is received. It's used for updating existing resources on the server.
     
  • doDelete(HttpServletRequest req, HttpServletResponse resp): This method is called when an HTTP DELETE request is received. It's used for deleting resources on the server.
     
  • service(HttpServletRequest req, HttpServletResponse resp): This method is called by the servlet container when any HTTP request is received. It examines the request method (GET, POST, etc.) & dispatches the request to the appropriate doXXX() method.


Let's see an example of an HTTP servlet that handles GET & POST requests:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().println("This is a GET request!");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String name = request.getParameter("name");
        response.setContentType("text/plain");
        response.getWriter().println("Hello, " + name + "!");
    }
}


This servlet extends HttpServlet & overrides the doGet() & doPost() methods to handle GET & POST requests differently. The doGet() method simply returns a plain text response, while the doPost() method retrieves a "name" parameter from the request & includes it in the response.

Note: When an HTTP request comes in, the servlet container calls the service() method, which then dispatches the request to the appropriate doGet() or doPost() method based on the request method.

Servlet API Package Hierarchy

The Servlet API is organized into several packages, each containing classes & interfaces for different aspects of servlet development. Let’s look at the package hierarchy:

  • javax.servlet: This is the core package of the Servlet API. It contains the basic Servlet interface, along with supporting classes & interfaces like ServletConfig, ServletContext, ServletRequest, & ServletResponse.
     
  • javax.servlet.http: This package builds on the core javax.servlet package & provides classes & interfaces specific to HTTP servlets. Key classes include HttpServlet, HttpServletRequest, HttpServletResponse, & HttpSession.
     
  • javax.servlet.annotation: This package provides annotations for servlet classes, such as @WebServlet for declaring a servlet without a web.xml file.
     
  • javax.servlet.descriptor: This package provides classes for representing elements of a web application deployment descriptor (web.xml file).
     
  • javax.servlet.http.part: This package provides classes for working with multipart requests, such as file uploads.
     
  • javax.servlet.jsp: This package provides classes & interfaces for JavaServer Pages (JSP). JSP is a technology that allows you to mix Java code & HTML in a single file to create dynamic web pages.
     
  • javax.servlet.jsp.jstl: This package provides the JavaServer Pages Standard Tag Library (JSTL), a collection of useful JSP tags for tasks like iterating over data, formatting output, & more.


In most cases, you'll primarily use the javax.servlet & javax.servlet.http packages for basic servlet development. The other packages provide additional functionality for more advanced use cases.

Let's see a simple example that shows the relationship between the Servlet & HttpServlet classes:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
    // This method is from the Servlet interface
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // Initialization code...
    }    
    // These methods are from the HttpServlet class
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // Handle GET request...
    }    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // Handle POST request...
    }
}


This servlet extends HttpServlet, which in turn extends GenericServlet & implements the Servlet interface. The init() method is from the Servlet interface, while the doGet() & doPost() methods are from the HttpServlet class.

Frequently Asked Questions

What's the difference between GenericServlet & HttpServlet?

GenericServlet is a protocol-independent servlet base class, while HttpServlet is an abstract class specifically designed for handling HTTP requests. HttpServlet provides methods like doGet() & doPost() for handling specific HTTP methods.

What's the purpose of the ServletConfig & ServletContext interfaces?

ServletConfig provides a servlet with its configuration data, while ServletContext represents the application context & allows servlets to share data & resources across an application.

What's a servlet container & what does it do?

A servlet container, like Apache Tomcat, is a component of a web server that interacts with Java servlets. It manages the lifecycle of servlets, forwards requests to them, & returns their responses to clients.

Conclusion

In this article, we've learned about the key components of the Java Servlet API. We've looked at the main javax.servlet package, which provides the basic Servlet interface & supporting classes. We've also examined the javax.servlet.http package, which adds classes specific to HTTP servlets, like HttpServlet, HttpServletRequest, & HttpServletResponse.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass