Request and Response Objects

Harry · 11 Sep 2026 · 9 views

Request and Response Objects

The HttpServletRequest and HttpServletResponse objects are your interface to the HTTP protocol. Understanding their methods is essential for building robust web applications.

HttpServletRequest Essentials

The request object wraps everything about the incoming HTTP request - the URL, headers, parameters, body, and session.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    // Request metadata
    String method = req.getMethod();       // GET, POST, etc.
    String uri = req.getRequestURI();       // /myapp/users
    String clientIp = req.getRemoteAddr();  // 127.0.0.1

    // Headers
    String accept = req.getHeader("Accept");
    String userAgent = req.getHeader("User-Agent");

    // Parameters (works for both query strings and form POST)
    String id = req.getParameter("id");
    String[] tags = req.getParameterValues("tags");

    // Attributes (set by servlets or filters)
    Object cached = req.getAttribute("cachedResult");
}

HttpServletResponse Essentials

The response object lets you control what gets sent back to the client - status code, headers, and body.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    resp.setStatus(HttpServletResponse.SC_OK);        // 200
    resp.setContentType("application/json");
    resp.setHeader("Cache-Control", "no-cache");

    PrintWriter out = resp.getWriter();
    out.println("{"message":"Success"}");
}

Setting Status Codes

Always set meaningful status codes. 200 for success, 201 for created, 400 for bad requests, 404 for not found, 500 for server errors. Use resp.sendError(code, message) for error responses - it generates a default error page.

Adding Headers

Headers control caching, content type, authentication, and more. Set them with resp.setHeader() or use convenience methods like resp.setContentType() and resp.setCharacterEncoding().

Key Points

  • HttpServletRequest provides access to method, URI, headers, parameters, and attributes.
  • HttpServletResponse controls status code, headers, and output body.
  • Use getParameter() for query params and form fields; getAttribute() for internal data.
  • Always set the correct HTTP status code for API responses.
  • sendError() generates standard error pages for error codes.
Share this post:

Comments (0)

Please login or register to comment.