Open In App

Handling HTTP GET and POST Requests in Servlets

Last Updated : 05 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Understanding how to handle HTTP GET and POST requests in Java Servlets is very important for developing robust web applications. In this article, we will explore how to handle HTTP GET and POST requests in servlets, their key differences, and when to use each. We will also optimize redundant servlet code to enhance maintainability.

Prerequisites: Before you move forward to the implementation part, ensure you have the following set up:

  • You must have Java Development Kit (JDK) installed on your system.
  • You must have the Apache Tomcat server (version 9 or higher is recommended).
  • Use an Integrated Development Environment (IDE) like Eclipse, IntelliJ IDEA, or NetBeans.
  • Familiarity with HTML forms and Java basics is helpful but not mandatory.

Understanding HTTP Methods in Servlets

HTTP provides various methods such as GET, POST, PUT, DELETE, etc. for client-server communication. In servlets, the two most commonly used methods are GET and POST. Here's how they work:

GET Method

  • Used to request data from the server.
  • Parameters are visible in the URL.
  • Suitable for non-sensitive data like search queries.

POST Method

  • Used to send data to the server.
  • Parameters are hidden in the request body.
  • Ideal for sensitive data like login credentials.
  • Preferred when modifying server-side data.

Note: By default, HTML forms use the GET method if the method attribute is not specified.

Implementation Steps

Follow these steps to handle HTTP GET and POST requests in Java Servlets:

Step 1: Setting Up Project

  • Create a Dynamic Web Project
    • In your IDE, create a new project and select Dynamic Web Project.
  • Configure Deployment Descriptor:
    • Ensure you have a web.xml file in the WEB-INF folder.
    • This file is required for servlet mapping if you are not using annotations.

Step 2: Observing GET Method Behavior

HTML Form for GET Request: Let us create an HTML form that sends two numbers to the server via the GET method. Save the below code as index.html:

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
  <form action="add" method="get">
  Enter num1: <input type ="text" name = "num1"><br>
  Enter num2: <input type ="text" name = "num2"><br>
  <input type="submit">
 </form>
</body>
</html>


Servlet to Handle GET Requests: Create a servlet class "AddServel" and then request is sent to the servlet mapped to /add. In the servlet, the doGet method processes GET requests:

Java
package com.LearnServlets;

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

public class AddServlet extends HttpServlet {

    public void doGet(HttpServletRequest req,
                      HttpServletResponse res)
        throws IOException
    {
        int num1
            = Integer.parseInt(req.getParameter("num1"));
        int num2
            = Integer.parseInt(req.getParameter("num2"));

        int result = num1 + num2;
        PrintWriter out = res.getWriter();
        out.println("The result is = " + result);
    }
}


Mapping the Servlet in web.xml: Ensure your web.xml contains the mapping for the servlet class (AddServlet):

XML
<web-app>
    <servlet>
        <servlet-name>AddServlet</servlet-name>
        <servlet-class>com.LearnServlets.AddServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddServlet</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>
</web-app>


Testing the GET Request:

  • Deploy your project to Tomcat and start the server.
  • Access index.html in the browser
  • Enter two numbers and submit the form.

Output:

executing-getMethod

Step 3: Using POST Method for Sensitive Data

To ensure parameters like passwords remain hidden, use the POST method.

Modify the Form for POST: Change the form’s method attribute to POST in index.html:

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
  <form action="add" method="post">
  Enter num1: <input type ="text" name = "num1"><br>
  Enter num2: <input type ="text" name = "num2"><br>
  <input type="submit">
 </form>
</body>
</html>


Let us see what happens if we do not update the Servlet to Handle POST Requests:

Java
package com.LearnServlets;

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

public class AddServlet extends HttpServlet {

    public void doGet(HttpServletRequest req,
                      HttpServletResponse res)
        throws IOException
    {
        int num1
            = Integer.parseInt(req.getParameter("num1"));
        int num2
            = Integer.parseInt(req.getParameter("num2"));

        int result = num1 + num2;
        PrintWriter out = res.getWriter();
        out.println("The result is = " + result);
    }
}

Output:

throwerror-

We can see a 405 HTTP error status in the browser while trying to handle the GET request. So, we need to update the servlet to handle the POST request.

Update the Servlet to Handle POST Requests: Add the doPost() method to AddServlet:

Java
package com.LearnServlets;

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

public class AddServlet extends HttpServlet {

    public void doPost(HttpServletRequest req,
                      HttpServletResponse res)
        throws IOException
    {
        int num1
            = Integer.parseInt(req.getParameter("num1"));
        int num2
            = Integer.parseInt(req.getParameter("num2"));

        int result = num1 + num2;
        PrintWriter out = res.getWriter();
        out.println("The result is = " + result);
    }
}


Testing the POST Request:

  • Deploy the project and restart the server.
  • Access the modified form in the browser.
  • Use tools like Postman to test POST requests explicitly.
  • To know, how to use Postman to test APIs, read this article: Test an API using Postman

Output:

Output

Behavior:

  • When using POST, parameters are hidden in the request body and do not appear in the URL.
  • Output remains the same, but it is more secure for sensitive data.

Step 4: Handling Both GET and POST Requests

To handle both GET and POST methods in the same servlet, avoid redundant code by creating a helper function.

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
  <form action="add" method="post">
  Enter num1: <input type ="text" name = "num1"><br>
  Enter num2: <input type ="text" name = "num2"><br>
  <input type="submit">
 </form>
</body>
</html>


Add a shared function for the core logic:

Java
package com.LearnServlets;

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

public class AddServlet extends HttpServlet {

    public void doPost(HttpServletRequest req,
                       HttpServletResponse res)
        throws IOException
    {
        fun(req, res);
    }

    public void doGet(HttpServletRequest req,
                      HttpServletResponse res)
        throws IOException
    {
        fun(req, res);
    }

    public void fun(HttpServletRequest req,
                    HttpServletResponse res)
        throws IOException
    {
        int num1
            = Integer.parseInt(req.getParameter("num1"));
        int num2
            = Integer.parseInt(req.getParameter("num2"));

        int result = num1 + num2;
        PrintWriter out = res.getWriter();
        out.println(
            "Executing the fun method. The result is = "
            + result);
    }
}

Output:

BothGetandPost

This program ensures a single logic path for both GET and POST.

Benefits:

  • Reduces redundancy.
  • Ensures a single logic path for both GET and POST

Choosing Between GET and POST

Use GET when,

  • The request does not modify server data.
  • Parameters are non-sensitive and can be bookmarked or cached.

Use POST when,

  • Handling sensitive data like passwords or personal information.
  • The request modifies server-side data (e.g., form submissions).
  • Always use POST for sensitive information.

Important Points:

  • Always use POST for sensitive information.
  • Use helper functions to avoid redundant code in servlets.
  • By effectively using doGet and doPost, you can ensure your web application handles HTTP requests securely and efficiently.

Article Tags :

Similar Reads