Handling HTTP GET and POST Requests in Java Servlets
Course: Advanced Java Training
Topic: Handling HTTP GET and POST Requests
Course Link: Advanced Java Training Course
Demo Link: Register for a Free Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to HTTP GET and POST Requests
HTTP (Hypertext Transfer Protocol) is the communication protocol used by web browsers, applications, and servers. When a user interacts with a web application, the browser sends an HTTP request to the server, and the server returns an HTTP response.
In Java web development, the HttpServlet class provides methods for handling different HTTP request methods. Two of the most frequently used methods are doGet() and doPost().
- GET: Commonly used to retrieve information from a server, such as displaying a product list or searching for records.
- POST: Commonly used to submit information to a server, such as registration details, feedback, or a new record.
The servlet container receives the request and dispatches it to the appropriate method of the servlet. The servlet processes the request and writes a response using HttpServletResponse.
2. Learning Objectives
After studying this topic, you will be able to:
- Understand the purpose of HTTP GET and POST requests.
- Explain the differences between GET and POST.
- Implement the
doGet() and doPost() methods.
- Read form parameters using
HttpServletRequest.
- Return HTML responses using
HttpServletResponse.
- Validate user input and handle errors appropriately.
- Map servlets using annotations and understand deployment requirements.
- Apply security and coding best practices when processing HTTP requests.
3. What Is an HTTP GET Request?
An HTTP GET request asks the server to return a representation of a resource. It is commonly used when a user opens a page, searches for information, or views a record.
For example, the following URL sends a search term to a web application:
http://localhost:8080/MyWebApp/search?q=java
In this example, q is a query parameter, and java is its value. A servlet can retrieve it using request.getParameter("q").
Characteristics of GET
- Request parameters are commonly included in the URL query string.
- URLs can be bookmarked and shared.
- Requests may be stored in browser history, server logs, or intermediary systems.
- GET requests can often be cached, depending on the response headers and caching rules.
- GET should be safe: it should not intentionally change application data.
- GET should be idempotent: repeating the same request should have the same intended effect on server state.
- GET is not suitable for confidential information in query parameters.
4. What Is an HTTP POST Request?
An HTTP POST request submits data to a server for processing. It is often used when creating a record, submitting a registration form, sending feedback, or performing an operation that may change application state.
For example, a registration form can submit a user's name and email address to a servlet through a POST request.
Characteristics of POST
- Form data is commonly transmitted in the request body.
- POST is useful for submitting data that may create or modify server-side resources.
- POST data is not normally displayed as query parameters in the URL.
- POST requests are not automatically safe or idempotent.
- POST is not inherently secure; HTTPS is needed to protect data in transit.
- Applications should validate submitted values before processing them.
- Depending on the content type, the request body may contain form data, JSON, or other data formats.
5. Difference Between GET and POST
| Feature |
GET |
POST |
| Primary purpose |
Retrieve information |
Submit information for processing |
| Servlet method |
doGet() |
doPost() |
| Typical parameter location |
URL query string |
Request body for form submissions |
| Bookmarking |
URLs with query parameters can be bookmarked |
Submitted request bodies are not normally bookmarked as a reusable request |
| Browser history |
Query parameters may appear in history |
Request body values are not normally displayed in the URL history |
| Caching |
May be cached according to HTTP rules and response headers |
Not normally cached by default |
| Data modification |
Should not intentionally change server state |
Often used for operations that change server state |
| Confidentiality |
Query parameters may be exposed in URLs and logs |
Body values are not shown in the URL, but HTTPS is still necessary |
| Typical use cases |
Search, listing, viewing details |
Registration, feedback, creating records |
Important: POST is not automatically more secure than GET. Use HTTPS, appropriate authorization, validation, and secure handling for both methods. Avoid putting passwords, access tokens, or other secrets in URLs.
6. How GET and POST Requests Work in a Servlet
- The user opens a page or submits an HTML form.
- The browser sends an HTTP request to the web server.
- The servlet container identifies the target servlet through its URL mapping.
- The container routes the request through the servlet's HTTP service mechanism.
- The
HttpServlet implementation dispatches the request to doGet(), doPost(), or another appropriate handler.
- The servlet reads parameters, validates input, and performs the required operation.
- The servlet sets response headers and writes the response body.
- The browser receives and displays the response.
7. Creating a Servlet That Handles GET and POST
To create a servlet, extend HttpServlet and override the methods required by your application. The example below uses Jakarta Servlet imports, suitable for compatible Jakarta EE servlet containers such as Tomcat 10 or later.
Example 1: Basic Servlet
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><body>");
out.println("<h1>Welcome to Java Servlets</h1>");
out.println("<p>This page was generated by a GET request.</p>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("name");
if (name == null || name.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Name is required."
);
return;
}
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><body>");
out.println("<h1>Form Submitted Successfully</h1>");
out.println("<p>Thank you for submitting the form.</p>");
out.println("</body></html>");
}
}
Explanation:
@WebServlet("/welcome") maps the servlet to the /welcome URL.
doGet() displays a welcome page when the browser sends a GET request.
doPost() reads the submitted name parameter and checks that it is present.
setContentType() defines the response content type and character encoding.
sendError() sends an HTTP error response when the input is invalid.
The example demonstrates request handling. In a production application, escape user-provided text before displaying it, or use a templating system that escapes output by default.
8. Handling GET Requests with Query Parameters
GET requests often pass information through the query string. Query parameters are useful for search forms, filters, pagination, and viewing individual records.
Example 2: Search Servlet
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String query = request.getParameter("q");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><body>");
if (query == null || query.isBlank()) {
out.println("<p>Enter a search term in the URL.</p>");
} else {
// Display a generic result message.
// Use an HTML-escaping utility before displaying user input.
out.println("<h2>Search request received</h2>");
out.println("<p>Search processing can be performed here.</p>");
}
out.println("</body></html>");
}
}
Example request URL:
http://localhost:8080/MyWebApp/search?q=java
The servlet receives java as the value of the q parameter. A real search application can pass the validated query to a service or database layer and return matching results.
Important Request Methods
| Method |
Purpose |
request.getParameter("q") |
Reads one request parameter as a string. |
request.getParameterValues("category") |
Reads multiple values for the same parameter. |
request.getParameterMap() |
Returns a map of request parameters. |
request.getQueryString() |
Returns the query string, if present. |
request.getMethod() |
Returns the HTTP method used for the request. |
9. Handling POST Requests with HTML Forms
HTML forms are commonly used to send data to a servlet. The form's method attribute specifies whether the browser sends a GET or POST request, and the action attribute specifies the destination URL.
Example 3: HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
</head>
<body>
<h1>Student Registration</h1>
<form action="register" method="post">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>
<br><br>
<button type="submit">Register</button>
</form>
</body>
</html>
How it works:
- The user enters a name and email address.
- The form sends a POST request to the
/register mapping.
- The browser includes form fields in the request body.
- The servlet reads values by using the input field names.
- The server validates the values and returns a response or processes the registration.
10. Processing Form Data in doPost()
Example 4: Registration Servlet
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/register")
public class RegistrationServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String email = request.getParameter("email");
if (name == null || name.isBlank()
|| email == null || email.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Name and email are required."
);
return;
}
// Validate the email format and apply business rules here.
// Save the record through a service or DAO if appropriate.
response.setContentType("text/html;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html><body>");
out.println("<h1>Registration Request Received</h1>");
out.println("<p>Your submitted information passed basic checks.</p>");
out.println("</body></html>");
}
}
This example checks that both fields are present. A production system should perform suitable validation, avoid duplicate registrations, handle database errors, and save data through a service or DAO layer. It should not assume that browser-side validation is sufficient.
11. Setting Character Encoding
Character encoding matters when forms contain names or text in languages other than English.
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
- Call
request.setCharacterEncoding("UTF-8") before reading request parameters when you need to control the decoding of submitted form data.
- Set the response content type and encoding before obtaining the response writer.
- Include a UTF-8 character set in the HTML document's metadata.
12. Understanding HttpServletRequest
HttpServletRequest provides information about the incoming request, including parameters, headers, the HTTP method, and the requested path.
| Method |
Description |
Example |
getParameter() |
Reads a named parameter. |
request.getParameter("name") |
getMethod() |
Gets the HTTP method. |
request.getMethod() |
getRequestURI() |
Gets the request URI path. |
request.getRequestURI() |
getHeader() |
Reads a request header. |
request.getHeader("User-Agent") |
getContextPath() |
Gets the application context path. |
request.getContextPath() |
getParameterValues() |
Reads multiple values for a parameter. |
request.getParameterValues("skills") |
13. Understanding HttpServletResponse
HttpServletResponse allows the servlet to control the response status, headers, content type, and body returned to the client.
| Method |
Purpose |
setContentType() |
Sets the response content type and optional character encoding. |
setStatus() |
Sets an HTTP response status code. |
sendError() |
Sends an error status and optionally an error message. |
sendRedirect() |
Redirects the client to another URL. |
getWriter() |
Obtains a character writer for a text response. |
setHeader() |
Sets a response header. |
14. Redirecting After a Successful POST
When a POST request successfully creates or updates data, a common approach is to redirect the browser to another page. This pattern is called Post/Redirect/Get (PRG). It helps prevent accidental duplicate form submissions when the user refreshes the resulting page.
// After successfully processing and saving the submitted data:
response.sendRedirect(
request.getContextPath() + "/registration-success"
);
The destination should be a valid page or servlet mapping. A redirect starts a new client request, typically a GET request, so do not expect the original POST body to be available at the destination.
15. Mapping Servlets to URLs
Servlet mappings connect a URL pattern to a servlet class. An annotation is a simple option for small applications.
@WebServlet("/register")
public class RegistrationServlet extends HttpServlet {
// Implement doGet() or doPost() as needed.
}
With a deployment descriptor, the mapping can be defined in WEB-INF/web.xml instead. Avoid unintentionally configuring conflicting mappings for the same URL.
16. Project Setup and Deployment
- Install a compatible Java Development Kit (JDK).
- Install an IDE such as IntelliJ IDEA or Eclipse.
- Set up a web application project with the appropriate Servlet API dependency.
- Create a servlet class that extends
HttpServlet.
- Map the servlet using
@WebServlet or web.xml.
- Create an HTML form or URL to send a request to the servlet.
- Deploy the application to a compatible servlet container.
- Open the application URL in a browser and test both GET and POST flows.
Compatibility note: Tomcat 10 and later use the jakarta.servlet package. Older Tomcat 9 applications commonly use javax.servlet. Use imports and dependencies that match the server version; do not mix both namespaces in the same application.
17. Testing GET and POST Requests
Testing GET
- Open a mapped servlet URL directly in the browser.
- Try query parameters, for example
/search?q=java.
- Test missing or empty parameters.
- Check the returned status code and content.
Testing POST
- Submit an HTML form with valid values.
- Submit the form with required values missing.
- Test invalid input and unexpected parameter values.
- Check server logs for errors and confirm that no duplicate data is created on repeated submissions.
- Use browser developer tools or an HTTP client to inspect the request method, headers, status, and response.
18. Common Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
| 404 Not Found |
Incorrect URL mapping or application context path |
Check the deployed application name and servlet mapping. |
| 405 Method Not Allowed |
The servlet does not support the requested method |
Implement the appropriate handler and submit the correct HTTP method. |
| Parameter returns null |
Incorrect input name or parameter not submitted |
Match the HTML field's name attribute with the parameter key. |
| Form data displays incorrectly |
Encoding mismatch |
Use UTF-8 consistently and set request encoding before reading parameters. |
| Servlet class not found |
Build or deployment problem |
Check compilation, project structure, dependencies, and server logs. |
| GET request changes stored data |
Incorrect use of GET |
Use POST or another suitable method for state-changing operations. |
| Duplicate form submission |
User refreshes or resubmits a POST |
Use Post/Redirect/Get and consider application-level idempotency where necessary. |
| Unexpected HTTP 500 |
Unhandled exception or server-side failure |
Inspect server logs, validate inputs, and handle expected failures appropriately. |
19. Security Best Practices
- Use HTTPS: Protect request and response data while it travels between the client and server.
- Validate input on the server: Treat all client-provided values as untrusted, even when HTML validation is present.
- Escape output: Escape user-supplied text before inserting it into HTML to reduce cross-site scripting (XSS) risks.
- Protect state-changing requests: Use CSRF protection where relevant, particularly for authenticated browser sessions.
- Do not expose secrets in URLs: URLs can be recorded in browser history, logs, and referrer data.
- Use authentication and authorization: Verify that the current user is permitted to access or modify the requested resource.
- Use parameterized SQL: If request values are used in database queries, use prepared statements instead of concatenating SQL strings.
- Handle errors safely: Avoid returning stack traces, credentials, or internal system details to users.
- Avoid shared mutable servlet fields: Servlet instances can process concurrent requests. Keep request-specific data in local variables or request-scoped objects.
- Apply request size limits: Set appropriate limits for uploaded or submitted content.
20. Mini Project: Student Registration Form
Objective: Create a simple student registration application that demonstrates GET and POST handling.
Project Requirements
- Create a page with a student registration form.
- Use GET to display the registration page.
- Use POST to submit the student's name, email, and course.
- Validate required fields on the server.
- Display a safe confirmation page after successful validation.
- Redirect after processing the POST request.
- Optionally, save student details in a database using JDBC and a DAO layer.
Suggested Project Structure
StudentRegistration/
├── src/main/java/
│ └── com/example/
│ ├── RegistrationServlet.java
│ ├── RegistrationService.java
│ └── StudentDAO.java
└── src/main/webapp/
├── registration.html
└── WEB-INF/
└── web.xml
The service and DAO classes are optional for a basic demonstration but are recommended as the project grows. Separate request handling, business logic, and database operations to make the application easier to test and maintain.
21. Interview Questions and Answers
Q1. What is the main difference between GET and POST?
Answer: GET is primarily used to retrieve a resource, while POST is commonly used to submit data for processing. GET parameters often appear in the URL, whereas form POST data is commonly sent in the request body.
Q2. Which methods handle GET and POST in HttpServlet?
Answer: The doGet() method handles GET requests, and the doPost() method handles POST requests.
Q3. What is HttpServletRequest?
Answer: It represents the incoming HTTP request and provides methods to read parameters, headers, the request URI, and other request details.
Q4. What is HttpServletResponse?
Answer: It represents the HTTP response that the servlet sends to the client. It is used to set status codes, headers, content types, and response content.
Q5. Is POST secure by default?
Answer: No. POST data is not normally displayed in the URL, but it still requires HTTPS and appropriate security controls to protect sensitive information.
Q6. Can GET requests be bookmarked?
Answer: Yes. GET URLs, including their query parameters, can generally be bookmarked and shared.
Q7. What happens if a servlet does not implement doPost()?
Answer: The default implementation in HttpServlet typically returns a 405 Method Not Allowed response for an unsupported POST method.
Q8. Why should request parameters be validated?
Answer: Client input can be missing, malformed, or malicious. Server-side validation helps preserve data integrity and reduces security risks.
Q9. What is Post/Redirect/Get?
Answer: It is a pattern in which a servlet processes a POST and then redirects the client to a separate page. This reduces accidental duplicate submissions caused by refreshing the result page.
Q10. Why should a servlet avoid storing request data in instance variables?
Answer: The container may handle multiple requests concurrently using the same servlet instance. Shared mutable fields can cause data races and leak data between requests.
22. Practice Exercises
- Create a servlet that displays a welcome message using GET.
- Build a search form that sends a query using GET.
- Create a feedback form that submits name and message using POST.
- Validate that a submitted email address is not empty and follows an acceptable format.
- Return suitable HTTP status codes for valid and invalid requests.
- Implement a registration form and redirect to a success page after processing.
- Modify a servlet to handle missing parameters without throwing unexpected exceptions.
- Build a student registration project with separate service and DAO classes.
- Test the application using a browser and an HTTP client.
- Review the application for XSS, CSRF, SQL injection, and authorization risks.
23. Quick Revision Checklist
- GET retrieves information and should not intentionally modify server state.
- POST submits data for processing and is often used for state-changing operations.
doGet() handles GET requests.
doPost() handles POST requests.
getParameter() reads a request parameter.
setContentType() configures the response content type and encoding.
- Validate input on the server before processing it.
- Use HTTPS to protect data in transit.
- Escape untrusted output and use parameterized SQL queries.
- Use Post/Redirect/Get when appropriate after successful form processing.
- Keep servlet code thread-safe and separate business logic from request handling.
- Match Servlet API imports to the deployed container version.
24. Official Documentation and Learning Resources
25. Conclusion
Handling HTTP GET and POST requests is a fundamental skill in Java web development. The doGet() method is generally used to retrieve information, while doPost() is commonly used to submit data for processing. Understanding request parameters, response handling, servlet mappings, validation, error management, and security helps developers build reliable web applications.
Practice by creating forms, implementing both request handlers, testing different inputs, and gradually integrating business logic and JDBC. For more structured learning, visit the Advanced Java Training course or register for a demo at JustAcademy.