Java Notes
Complete guide to HttpServletRequest and HttpServletResponse objects - reading parameters, headers, handling request data, setting responses, and content types.
Overview
Every servlet method receives two objects:
- HttpServletRequest — Contains all information about the client's request
- HttpServletResponse — Used to send the response back to the client
These are the most important objects in servlet programming.
Getting Request Headers
// Specific header
String userAgent = request.getHeader("User-Agent");
String contentType = request.getHeader("Content-Type");
String authorization = request.getHeader("Authorization");
String acceptLanguage = request.getHeader("Accept-Language");
// All headers
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println(headerName + ": " + headerValue);
}
// Integer and Date headers
int contentLength = request.getIntHeader("Content-Length");
long ifModifiedSince = request.getDateHeader("If-Modified-Since");Request Information Methods
@WebServlet("/request-info")
public class RequestInfoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Request Information</h2>");
out.println("<table border=\"1\">");
out.println("<tr><td>Method</td><td>" + request.getMethod() + "</td></tr>");
out.println("<tr><td>Request URI</td><td>" + request.getRequestURI() + "</td></tr>");
out.println("<tr><td>Request URL</td><td>" + request.getRequestURL() + "</td></tr>");
out.println("<tr><td>Context Path</td><td>" + request.getContextPath() + "</td></tr>");
out.println("<tr><td>Servlet Path</td><td>" + request.getServletPath() + "</td></tr>");
out.println("<tr><td>Path Info</td><td>" + request.getPathInfo() + "</td></tr>");
out.println("<tr><td>Query String</td><td>" + request.getQueryString() + "</td></tr>");
out.println("<tr><td>Protocol</td><td>" + request.getProtocol() + "</td></tr>");
out.println("<tr><td>Scheme</td><td>" + request.getScheme() + "</td></tr>");
out.println("<tr><td>Server Name</td><td>" + request.getServerName() + "</td></tr>");
out.println("<tr><td>Server Port</td><td>" + request.getServerPort() + "</td></tr>");
out.println("<tr><td>Remote Addr</td><td>" + request.getRemoteAddr() + "</td></tr>");
out.println("<tr><td>Remote Host</td><td>" + request.getRemoteHost() + "</td></tr>");
out.println("<tr><td>Content Type</td><td>" + request.getContentType() + "</td></tr>");
out.println("<tr><td>Content Length</td><td>" + request.getContentLength() + "</td></tr>");
out.println("<tr><td>Character Encoding</td><td>" + request.getCharacterEncoding() + "</td></tr>");
out.println("</table>");
}
}Reading Request Body (JSON)
@WebServlet("/api/users")
public class UserApiServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Read JSON body
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String jsonBody = sb.toString();
// Parse JSON (using a library like Gson or Jackson)
// For simplicity, manual parsing shown here
System.out.println("Received JSON: " + jsonBody);
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_CREATED);
response.getWriter().println("{\"status\": \"created\", \"received\": " + jsonBody + "}");
}
}Request Attributes (for forwarding data)
// Setting attributes (in first servlet)
request.setAttribute("userList", users);
request.setAttribute("totalCount", users.size());
request.setAttribute("message", "Data loaded successfully");
// Getting attributes (in forwarded servlet/JSP)
List<User> users = (List<User>) request.getAttribute("userList");
int count = (int) request.getAttribute("totalCount");
// Remove attribute
request.removeAttribute("message");HttpServletResponse — Sending Data to Client
Setting Response Content Type
// HTML response
response.setContentType("text/html");
// JSON response
response.setContentType("application/json");
// Plain text
response.setContentType("text/plain");
// XML response
response.setContentType("application/xml");
// PDF file
response.setContentType("application/pdf");
// Set character encoding
response.setCharacterEncoding("UTF-8");
// Combined
response.setContentType("text/html;charset=UTF-8");Writing Response Body
// Using PrintWriter (for text/character data)
PrintWriter out = response.getWriter();
out.println("<html><body>Hello World</body></html>");
// Using OutputStream (for binary data — images, files)
ServletOutputStream os = response.getOutputStream();
byte[] fileData = Files.readAllBytes(Paths.get("/path/to/image.png"));
os.write(fileData);
os.flush();⚠️ Important: You cannot use bothgetWriter()andgetOutputStream()on the same response. Doing so throwsIllegalStateException.
Setting Response Headers
// Set headers
response.setHeader("X-Custom-Header", "CustomValue");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// Add headers (allows multiple values for same header)
response.addHeader("Set-Cookie", "theme=dark; Path=/");
response.addHeader("Set-Cookie", "lang=en; Path=/");
// Numeric headers
response.setIntHeader("Refresh", 5); // Refresh page every 5 secondsSetting Status Codes
// Success codes
response.setStatus(HttpServletResponse.SC_OK); // 200
response.setStatus(HttpServletResponse.SC_CREATED); // 201
response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204
// Redirect codes
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); // 301
response.sendRedirect("/new-location"); // 302
// Client error codes
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid input"); // 400
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Login required"); // 401
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied"); // 403
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found"); // 404
// Server error codes
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error"); // 500File Download Response
Complete Request-Response Example
Request Methods Summary Table
| Method | Returns | Description |
|---|---|---|
getParameter(name) | String | Single form/query parameter |
getParameterValues(name) | String[] | Multiple values for same param |
getParameterMap() | Map | All parameters |
getHeader(name) | String | HTTP header value |
getMethod() | String | GET, POST, PUT, DELETE |
getRequestURI() | String | URI path (no host) |
getRequestURL() | StringBuffer | Full URL |
getContextPath() | String | Application context |
getQueryString() | String | Raw query string |
getRemoteAddr() | String | Client IP address |
getReader() | BufferedReader | Request body reader |
getInputStream() | InputStream | Binary request body |
getAttribute(name) | Object | Request attribute |
getSession() | HttpSession | Session object |
getCookies() | Cookie[] | All cookies |
Response Methods Summary Table
| Method | Purpose |
|---|---|
setContentType(type) | Set MIME type |
setCharacterEncoding(enc) | Set encoding |
setStatus(code) | Set HTTP status |
sendError(code, msg) | Send error response |
sendRedirect(url) | 302 redirect |
setHeader(name, value) | Set response header |
addHeader(name, value) | Add header (multi-value) |
getWriter() | Get character writer |
getOutputStream() | Get binary output stream |
addCookie(cookie) | Add cookie to response |
setContentLength(len) | Set content length |
Common Mistakes
- Calling getWriter() and getOutputStream() on same response — IllegalStateException
- Writing response after sendRedirect() — Response already committed
- Not checking null for getParameter() — NullPointerException
- Not setting content type before writing — Browser may not render properly
- Reading body in doGet() — GET requests typically don't have a body
🔥 Interview Questions
Q1. What are the important methods of HttpServletRequest?
Answer: getParameter() — form data, getAttribute()/setAttribute() — request attributes, getSession() — session access, getHeader() — HTTP headers, getMethod() — HTTP method, getRequestURI() — URI, getContextPath() — app context, getRemoteAddr() — client IP.
Q2. What is the difference between getParameter() and getAttribute()?
Answer: getParameter() — data that came from the client (form fields, query string), returns String, read-only. getAttribute() — server-side data sharing (between servlets via forward), returns Object, read-write via setAttribute().
Q3. What is the difference between Forward and Redirect?
Answer:
| Feature | Forward | Redirect |
|---|---|---|
| Control | Server-side | Client-side (new request) |
| URL | Same (browser doesn't know) | Changes in browser |
| Request data | Preserved (same request) | Lost (new request) |
| Speed | Faster (single request) | Slower (two round-trips) |
| Use | Internal navigation | External URL, after POST |
Q4. sendRedirect() vs RequestDispatcher.forward()?
Answer: sendRedirect("url") — sends a 302 response to the browser, the browser makes a new request. RequestDispatcher.forward(req, res) — handled internally by the server, the client is unaware. sendRedirect is used in the POST-Redirect-GET pattern.
Q5. Request Scope vs Session Scope vs Application Scope?
Answer: Request: Share data within a single request (between forwards). Session: Persist within a user session (login info). Application: Shared across all sessions (global config). As scope increases, memory usage and concurrency concerns increase.
Q6. How to set content type in HttpServletResponse?
Answer: response.setContentType("text/html") or response.setContentType("application/json"). This tells the browser how to parse the response. Set this BEFORE getting writer/output stream.
Q7. How to add headers in the Response?
Answer: response.setHeader("name", "value") — single value. response.addHeader("name", "value") — multiple values for the same header. Use setStatus() to set the HTTP status code. Common: Content-Type, Cache-Control, Location (redirect).
Q8. How to read the Request body (POST data)?
Answer: Form data: request.getParameter("field"). JSON body: request.getReader() gives a BufferedReader, read and parse JSON from it. Binary data: use request.getInputStream().
Q9. How to handle file upload in a servlet?
Answer: Use the @MultipartConfig annotation. Access the file using request.getPart("file") or request.getParts(). The Part interface provides filename, size, content type, and input stream.
Q10. What is Response buffering?
Answer: The response does not go to the client immediately — it is collected in a buffer. Set buffer size with response.setBufferSize(8192). Manually flush with response.flushBuffer(). The buffer automatically flushes when full or when the response is committed. Headers can only be set before commit.
Summary
In this chapter, we learned about Request and Response Objects in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Request and Response Objects.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, request
Related Java Master Course Topics