Handling HTTP GET and POST Requests in Servlets
Last Updated :
05 Feb, 2025
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:

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:
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:
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:
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.
Similar Reads
Servlet - Client HTTP Request When the user wants some information, he/she will request the information through the browser. Then the browser will put a request for a web page to the webserver. It sends the request information to the webserver which cannot be read directly because this information will be part of the header of t
3 min read
Servlet - HttpSession Login and Logout Example In general, the term "Session" in computing language, refers to a period of time in which a user's activity happens on a website. Whenever you login to an application or a website, the server should validate/identify the user and track the user interactions across the application. To achieve this, J
8 min read
Servlet - Event and Listener The term "event" refers to the occurrence of something. An event occurs when the state of an object changes. When these exceptions occur, we can conduct certain crucial actions, such as collecting total and current logged-in users, establishing database tables when deploying the project, building da
8 min read
Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse What is Servlet Collaboration? The exchange of information among servlets of a particular Java web application is known as Servlet Collaboration. This enables passing/sharing information from one servlet to the other through method invocations. What are the principle ways provided by Java to achiev
4 min read
Servlet - HttpSessionEvent and HttpSessionListener In Java, HttpSessionEvent is a class, which is representing event notifications for changes or updates to sessions within a web application. Similarly, the interface for this event is HttpSessionListener, which is for receiving notification events about HttpSession lifecycle changes. As a means to,
3 min read
Servlet - Fetching Result Servlet is a simple java program that runs on the server and is capable to handle requests from the client and generate dynamic responses for the client. How to Fetch a Result in Servlet? It is depicted below stepwise as shown below as follows: You can fetch a result of an HTML form inside a Servlet
3 min read