Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Servlets · Lesson 4

GET vs POST Handling

Choosing GET and POST

GET requests retrieve a resource and place parameters in the URL, while POST requests submit data in the request body. The distinction matters for caching, bookmarking, privacy, and the way a server processes a request. A servlet should select the method that matches the action a client is performing.

Handling Both Methods

Override doGet and doPost on the same servlet when a page displays a form and then processes its submission. Keep the two flows explicit so readers and clients can understand the contract.

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SearchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String searchTerm = request.getParameter("q");
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Searching for: " + searchTerm);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String emailAddress = request.getParameter("email");
        response.sendRedirect("/signup-success?email=" + emailAddress);
    }
}

Method Comparison

AspectGETPOST
Typical purposeRead dataCreate or change data
ParametersQuery stringRequest body
BookmarkableYesUsually no
CacheableOftenRarely
Sensitive dataAvoid in URLPrefer request body with HTTPS

Common Mistake and Practices

Common Mistake: Using GET for an operation that changes server state. Browsers, crawlers, or refreshes may repeat GET requests, so state-changing work belongs behind POST or another appropriate method.

  • Validate parameters before using them.
  • Encode redirect parameters safely.
  • Use HTTPS for credentials and personal data.
  • Return a clear status code for invalid requests.
  • Use Post/Redirect/Get after successful form submission.

Real-World Use Case

A product search page uses GET so a result URL can be shared, while an account registration form uses POST so submitted data is placed in the request body and the action is not accidentally repeated by a bookmarked URL.

Quiz Check

Quick Knowledge Test

Loading quiz questions...