HttpServlet Class Example Tutorial

The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests.
Unlike GenericServlet, the HTTP Servlet doesn’t override the service() method. Instead it overrides the doGet() method or doPost() method or both. The doGet() method is used for getting the information from the server while the doPost() method is used for sending information to the server.

HttpServlet Class Diagram

Below HttpServlet class diagram shows HttpServlet class extends GenericServlet and shows a list of HttpServlet class methods.

HttpServlet Class Methods

Let's list out all the HttpServlet class methods:
  • protected void doDelete(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a DELETE request.
  • protected void doGet(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a GET request.
  • protected void doHead(HttpServletRequest req, HttpServletResponse resp) - This method receives an HTTP HEAD request from the protected service method and handles the request.
  • protected void doOptions(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a OPTIONS request.
  • protected void doPost(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a POST request.
  • protected void doPut(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a PUT request.
  • protected void doTrace(HttpServletRequest req, HttpServletResponse resp) - This method is called by the server (via the service method) to allow a servlet to handle a TRACE request.
  • protected long getLastModified(HttpServletRequest req) - This method returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1, 1970 GMT.
  • protected void service(HttpServletRequest req, HttpServletResponse resp) - This method receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class.
  • void service(ServletRequest req, ServletResponse res) - This method dispatches client requests to the protected service method.

HttpServlet Class Example

In this example, we will demonstrate the usage of doGet() and doPost() methods with an example.
Let's add servlet 4.0.1 dependency to pom.xml:
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
If your project is not a maven project then you can download the jar file and keep in the classpath.

Handling HTTP GET Request Example

Here we will develop a servlet that handles an HTTP GET request. We will create a Student registration form and the servlet is invoked when a form on a web page is submitted. The example contains a Student registration JSP form student.jsp and a servlet is defined in StudentServlet.java.
Let's create a student.jsp file which contains a Student registration HTML form.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP Actions Example</title>
</head>
<body>

<h1> Student Registration Page</h1>
 <form action="<%= request.getContextPath() %>/StudentServlet" method="get">
  First Name: <input type="text" name="firstName">
  <br> <br> 
  
  Last Name: <input type="text" name="lastName">
  <br> <br> 
  
  Email ID: <input type="email" name="emailId">
  <br> <br> 
  
  Password: <input type="password" name="password"><br>
  
  <br> 
  <input type="submit" value="register">
 </form>
</body>
</html>
Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.
Let's run this example in tomcat server and hit http://localhost:8080/java-servlet-tutorial/student.jsplink into a browser will result below web page: 
 Let's create StudentServlet.java file and enter the following code into it. The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.
package net.javaguides.servlet.tutorial.examples;

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("/StudentServlet")
public class StudentServlet extends HttpServlet {

    private static final long serialVersionUID = 1 L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String firstName = req.getParameter("firstName");
        String lastName = req.getParameter("lastName");
        String emailId = req.getParameter("emailId");
        String password = req.getParameter("password");

        resp.setContentType("text/html");
        PrintWriter printWriter = resp.getWriter();
        printWriter.print("<html>");
        printWriter.print("<body>");
        printWriter.print("<h1>Student Resistration Form Data</h1>");
        printWriter.print("<p> firstName :: " + firstName + "</p>");
        printWriter.print("<p> lastName :: " + firstName + "</p>");
        printWriter.print("<p> firstName :: " + firstName + "</p>");
        printWriter.print("<p> firstName :: " + firstName + "</p>");
        printWriter.print("</body>");
        printWriter.print("</html>");
        printWriter.close();

        System.out.println("firstName :: " + firstName);
        System.out.println("lastName :: " + lastName);
        System.out.println("emailId :: " + emailId);
        System.out.println("password :: " + password);
    }
}
Let's fill above Student registration HTML form and hit submit button will result below page:

Handling HTTP POST Request Example

Here we will develop a servlet that handles an HTTP POST request. We will continue with the same Student registration HTML form and we will change the form action method from "get" to "post":
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP Actions Example</title>
</head>
<body>

<h1> Student Registration Page</h1>
 <form action="<%= request.getContextPath() %>/StudentServlet" method="post">
  First Name: <input type="text" name="firstName">
  <br> <br> 
  
  Last Name: <input type="text" name="lastName">
  <br> <br> 
  
  Email ID: <input type="email" name="emailId">
  <br> <br> 
  
  Password: <input type="password" name="password"><br>
  
  <br> 
  <input type="submit" value="register">
 </form>
</body>
</html>
Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP POST request.
Let's run this example in tomcat server and hit http://localhost:8080/java-servlet-tutorial/student.jsplink into a browser will result below web page:
Let's create StudentServlet.java file and enter the following code into it. The doPost( ) method is overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.
package net.javaguides.servlet.tutorial.examples;

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("/StudentServlet")
public class StudentServlet extends HttpServlet {

    private static final long serialVersionUID = 1 L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String firstName = req.getParameter("firstName");
        String lastName = req.getParameter("lastName");
        String emailId = req.getParameter("emailId");
        String password = req.getParameter("password");

        resp.setContentType("text/html");
        PrintWriter printWriter = resp.getWriter();
        printWriter.print("<html>");
        printWriter.print("<body>");
        printWriter.print("<h1>Student Resistration Form Data</h1>");
        printWriter.print("<p> firstName :: " + firstName + "</p>");
        printWriter.print("<p> lastName :: " + firstName + "</p>");
        printWriter.print("<p> firstName :: " + firstName + "</p>");
        printWriter.print("<p> firstName :: " + firstName + "</p>");
        printWriter.print("</body>");
        printWriter.print("</html>");
        printWriter.close();

        System.out.println("firstName :: " + firstName);
        System.out.println("lastName :: " + lastName);
        System.out.println("emailId :: " + emailId);
        System.out.println("password :: " + password);
    }
}
Let's fill above Student registration form and hit submit button will result below page:

Related Servlet Examples

Check out complete Servlet 4 tutorial at Servlet Tutorial

Reference


Comments

  1. Hi,
    In which situation the HTTPResquest changes into HTTPServletRequest and in which situation HTTPServletResponse changes into HTTPResponse. Whether the Servlet or the Web Container does the conversion.

    Thanks.

    ReplyDelete

Post a Comment