Monday, 24 March 2014

Servlets : HTTPServlet

🚀 Master Java Servlets & Web Development!

Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical web architecture guides!

👉 Click Here to Subscribe Now

What is HttpServlet in Java Servlets?

In Java web development, HttpServlet is an abstract class located in the jakarta.servlet.http (or javax.servlet.http) package that provides an HTTP-specific implementation of the GenericServlet class.

While the basic Servlet interface and GenericServlet class are protocol-independent, HttpServlet is specially tailored for web applications running over the HTTP protocol. It simplifies handling HTTP requests by providing specialized methods for GET, POST, PUT, DELETE, and other standard HTTP actions.

The Servlet Inheritance Hierarchy

Understanding where HttpServlet sits in the hierarchy clarifies how servlets operate under the hood:

  • Servlet (Interface): Declares core lifecycle methods: init(), service(), and destroy().
  • GenericServlet (Abstract Class): Implements Servlet, providing protocol-independent default implementations while leaving service() abstract.
  • HttpServlet (Abstract Class): Extends GenericServlet and overrides the generic service() method to dispatch incoming requests to HTTP-specific handler methods.

Key Methods of HttpServlet

When you extend HttpServlet, you typically override one or more of its HTTP verb methods instead of overriding service() directly:

  • doGet(HttpServletRequest req, HttpServletResponse resp): Handles HTTP GET requests (retrieving web pages or fetching search results).
  • doPost(HttpServletRequest req, HttpServletResponse resp): Handles HTTP POST requests (submitting form data, passwords, or file uploads).
  • doPut(HttpServletRequest req, HttpServletResponse resp): Handles HTTP PUT requests (updating existing resources).
  • doDelete(HttpServletRequest req, HttpServletResponse resp): Handles HTTP DELETE requests (deleting resources).
  • doHead(), doOptions(), doTrace(): Support advanced HTTP protocol capabilities.

Basic HttpServlet Code Example

Creating a modern servlet by extending HttpServlet and mapping it using the @WebServlet annotation:

package com.ramnjava.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloHttpServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<h2>Hello from HttpServlet!</h2>");
  }
}

Why Do We Almost Always Use HttpServlet?

  • Automatic Method Dispatching: The internal service() method automatically detects the HTTP request method and delegates control to doGet(), doPost(), etc.
  • HTTP Object Support: Provides type-safe access to HttpServletRequest and HttpServletResponse, allowing easy access to cookies, sessions, headers, and query parameters.
  • Industry Standard: Standard enterprise Java web frameworks (such as Spring MVC and Jakarta Faces) build their dispatching engines on top of HttpServlet.

📺 Related Servlets Architecture Tutorials

Learn more about servlet internals and request handling from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=JUFBrXOgAlk

Click the below Image to Enlarge
HTTPServlet

HTTPServlet Project Dir Structure

HTTPServlet

HelloHttpServlet.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.io.IOException;
import java.io.PrintWriter;

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 HelloHttpServlet extends HttpServlet
{

  private static final long serialVersionUID = 1L;

  ServletConfig             config           = null;

  public void init( ServletConfig config )
  {
    this.config = config;
    System.out.println("-----------------------------------------------------");
    System.out.println("init method has been called and servlet is initialized");
    System.out.println("-----------------------------------------------------");
  }

  public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
                  IOException
  {

    System.out.println("-----------------------------------------------------");
    System.out.println("doGet method has been called");
    System.out.println("-----------------------------------------------------");

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    out.print("<html><body>");
    out.print("<b>hello HTTP servlet</b>");
    out.print("</body></html>");
  }

  public void destroy()
  {
    System.out.println("-----------------------------------------------------");
    System.out.println("destroy method has been called and servlet is destroyed");
    System.out.println("-----------------------------------------------------");
  }

}

web.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
  <display-name>HelloHttpServlet</display-name>
  <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
  <servlet>
    <servlet-name>HelloHttpServlet</servlet-name>
    <servlet-class>HelloHttpServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloHttpServlet</servlet-name>
    <url-pattern>/helloHttpServlet</url-pattern>
  </servlet-mapping>
</web-app>

index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>HelloHttpServlet</title>
</head>
<body>
<p>
<h3>HelloHttpServlet</H3>
<p></p>
<ul>

<li><a href="helloHttpServlet">HelloHttpServlet</a></li>

</ul>
</body></html>

Environment Used: 

JDK version :1.6.0_30
Tomcat version : 7.0.50 

To Download HTTPServletApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/HTTPServletApp.zip?attredirects=0&d=1 

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • 1 comment:

    Tutorials