By WebNest Studio Engineering Team
Advanced Java Tutorial
Request and Response Objects
Every time a servlet's doGet or doPost method runs, the container hands it two objects: an HttpServletRequest representing everything the client sent, and an HttpServletResponse representing everything the servlet will send back. Almost all servlet logic revolves around reading from the request and writing to the response.
HttpServletRequest — Reading Client Data
The request object exposes form data, URL query parameters, headers, cookies, and metadata about the connection.
getParameter(String name)— returns a single form field or query string value as a String (or null if absent).getParameterValues(String name)— returns an array, used for multi-value fields like checkboxes.getHeader(String name)— reads an HTTP request header, such asUser-AgentorAuthorization.getMethod(),getRequestURI(),getRemoteAddr()— metadata about the request itself.getAttribute()/setAttribute()— a per-request storage area, commonly used to pass data to a JSP via forward.
HttpServletResponse — Writing Back to the Client
The response object controls the status code, headers, and body sent back. Setting the content type before writing the body matters because it tells the browser how to interpret what follows.
setContentType(String type)— e.g."text/html"or"application/json"; must be called before getWriter() for correct behavior.getWriter()— returns a PrintWriter for writing character (text) output, such as HTML.getOutputStream()— returns a stream for binary output, such as an image or file download.setStatus(int sc)/sendError(int sc)— sets the HTTP status code, e.g. 404 or 500.sendRedirect(String url)— sends an HTTP redirect, instructing the browser to make a new request.
A Note on Character Encoding
Because request parameters and response bodies are ultimately byte streams, character encoding matters for anything beyond plain ASCII. Calling request.setCharacterEncoding("UTF-8") before reading any parameters, and response.setCharacterEncoding("UTF-8") (or including it in setContentType, e.g. "text/html;charset=UTF-8") before writing, avoids garbled text for non-English input.
Example
Reading form parameters and headers, then writing an HTML response
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String userAgent = request.getHeader("User-Agent");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (username == null || username.trim().isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
out.println("<h3>Error: username is required</h3>");
return;
}
out.println("<html><body>");
out.println("<h3>Welcome, " + username + "!</h3>");
out.println("<p>Detected browser info: " + userAgent + "</p>");
out.println("</body></html>");
}
}
Form submitted with username=Ananya:
Welcome, Ananya!
Detected browser info: Mozilla/5.0 (...) Chrome/...
Form submitted with empty username:
HTTP 400 response body: Error: username is required
Common Mistakes
- Calling getParameter() for a form field name that does not match the HTML form's "name" attribute exactly (case-sensitive) and getting null.
- Calling response.getWriter() before response.setContentType(), which can cause the content type to be ignored by some containers.
- Mixing getWriter() and getOutputStream() calls on the same response, which throws an IllegalStateException.
- Forgetting to call setCharacterEncoding("UTF-8") before reading parameters that contain non-ASCII text, resulting in garbled characters.
Exercise
Using the lesson's Reading form parameters and headers, then writing an HTML response example, create a small implementation or design sketch that demonstrates HttpServletRequest carries everything the client sent: parameters, headers, attributes, and connection metadata.. Add a test case or scenario that would catch Calling getParameter() for a form field name that does not match the HTML form's "name" attribute exactly (case-sensitive) and getting null., and describe the expected result.
Show hints
- Start with HttpServletRequest — Reading Client Data and compare your approach with Reading form parameters and headers, then writing an HTML response. Identify the decision or behavior the lesson recommends.
- Walk through your scenario step by step. Confirm that it follows HttpServletRequest carries everything the client sent: parameters, headers, attributes, and connection metadata. and that it would catch the failure described by Calling getParameter() for a form field name that does not match the HTML form's "name" attribute exactly (case-sensitive) and getting null..
Quick quiz
1. Which choice is a mistake to avoid in Request and Response Objects?
- A. HttpServletRequest carries everything the client sent: parameters, headers, attributes, and connection metadata.
- B. Calling getParameter() for a form field name that does not match the HTML form's "name" attribute exactly (case-sensitive) and getting null.
- C. Calling response.getWriter() before response.setContentType(), which can cause the content type to be ignored by some containers.
Show answer
B. Avoid this approach: Calling getParameter() for a form field name that does not match the HTML form's "name" attribute exactly (case-sensitive) and getting null. The lesson recommends: HttpServletRequest carries everything the client sent: parameters, headers, attributes, and connection metadata.
Interview questions
How would you apply the guidance in HttpServletRequest — Reading Client Data to a real task, and what failure would you guard against?
Show answer
HttpServletRequest carries everything the client sent: parameters, headers, attributes, and connection metadata. Apply this in HttpServletRequest — Reading Client Data; the example Reading form parameters and headers, then writing an HTML response shows one way to do it. Avoid Calling getParameter() for a form field name that does not match the HTML form's "name" attribute exactly (case-sensitive) and getting null. and explain how your implementation or design prevents that failure.
Key Points to Remember
- HttpServletRequest carries everything the client sent: parameters, headers, attributes, and connection metadata.
- HttpServletResponse controls what goes back: status code, headers, and body via getWriter() or getOutputStream().
- Set content type and character encoding before writing to the response body.
- getParameter() always returns a String or null — never assume a value was supplied.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
These examples need a JDK project with their libraries on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering