Servlet Request and Response Objects
HttpServletRequest and HttpServletResponse are the primary interfaces for reading client data and sending responses. Every Servlet method receives these two objects.
HttpServletRequest — Reading Data
- getParameter("name") — Read form fields and query string values.
- getParameterValues("hobby") — Read multi-value fields like checkboxes.
- getHeader("User-Agent") — Read HTTP headers.
- getSession() — Access or create an HTTP session.
- getRequestDispatcher("/page.jsp").forward() — Forward to another resource.
- getCookies() — Read cookies sent by the browser.
HttpServletResponse — Sending Data
- setContentType("application/json") — Set MIME type.
- setStatus(HttpServletResponse.SC_NOT_FOUND) — Set HTTP status code.
- sendRedirect("/login") — Redirect browser to another URL.
- addCookie(new Cookie("theme", "dark")) — Set cookies.
- getWriter() — Get PrintWriter for text responses.
- getOutputStream() — Get stream for binary data (images, files).
Practical Example
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String query = req.getParameter("q");
if (query == null || query.isBlank()) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing query");
return;
}
resp.setContentType("application/json");
resp.getWriter().printf("{"query":"%s","results":[]}", query);
}
}Request Scope vs Session Scope
Use request attributes (req.setAttribute) for data passed between Servlets and JSPs within a single request. Use session attributes (req.getSession().setAttribute) for user-specific data that persists across multiple requests, such as login state or shopping cart contents.
Frequently Asked Questions
Can I read the request body in doGet()?▼
GET requests typically have no body. Parameters come from the query string via getParameter(). For JSON bodies, read from req.getReader() or req.getInputStream() in doPost().
