Handling GET and POST Requests
Handling GET and POST Requests
HTTP defines several methods, but GET and POST cover the vast majority of web interactions. GET retrieves data. POST submits data. Your servlet must handle both correctly.
GET Requests
A GET request carries parameters in the URL query string. Use getParameter() to read them. GET requests should never modify server state - they are safe to bookmark, cache, and repeat.
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String query = req.getParameter("q");
if (query == null || query.isBlank()) {
query = "";
}
List<String> results = searchService.search(query);
req.setAttribute("results", results);
req.getRequestDispatcher("/WEB-INF/views/search.jsp")
.forward(req, resp);
}
}
POST Requests
A POST request sends data in the request body. Use it for creating or updating resources. Always validate and sanitize POST data.
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
String email = req.getParameter("email");
String password = req.getParameter("password");
if (name == null || email == null || password == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
"All fields are required");
return;
}
userService.register(name, email, password);
resp.sendRedirect(req.getContextPath() + "/register?success=true");
}
}
Forward vs Redirect
A forward happens server-side. The browser URL does not change. A redirect sends a 302 response and the browser makes a new request to a different URL. Use forwards for internal dispatch and redirects after POST to prevent duplicate form submissions.
Form Handling Pattern
The standard pattern for HTML forms: display the form via GET, process the submission via POST, and redirect back on success.
Key Points
- GET reads data; POST writes data.
- Use
getParameter()to read form fields and query strings. - Forward (server-side) keeps the URL unchanged; redirect (client-side) changes it.
- Always validate POST parameters before processing.
- Redirect after POST to prevent duplicate submissions.