Tutorials Logic, IN info@tutorialslogic.com

Servlet Request Response Objects: Tutorial, Examples, FAQs & Interview Tips

Servlet Request Response Objects

Servlet Request Response Objects is an important Servlet topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Servlet Request Response Objects solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of Servlet Request Response Objects should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Servlet Request Response Objects should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the servlet > request-response page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

HttpServletRequest

The HttpServletRequest object provides all information about the incoming HTTP request. It extends ServletRequest with HTTP-specific methods.

HttpServletRequest Methods

HttpServletRequest Methods
@WebServlet("/request-demo")
public class RequestDemoServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // ===== Request Parameters =====
        String name   = req.getParameter("name");           // Single value
        String[] tags = req.getParameterValues("tags");     // Multiple values (checkboxes)
        java.util.Map<String, String[]> params = req.getParameterMap(); // All params

        // ===== Request Headers =====
        String userAgent    = req.getHeader("User-Agent");
        String contentType  = req.getContentType();
        String accept       = req.getHeader("Accept");
        java.util.Enumeration<String> headerNames = req.getHeaderNames();

        // ===== Request Info =====
        String method      = req.getMethod();          // GET, POST, etc.
        String uri         = req.getRequestURI();      // /myapp/request-demo
        String url         = req.getRequestURL().toString(); // http://localhost:8080/myapp/request-demo
        String contextPath = req.getContextPath();     // /myapp
        String servletPath = req.getServletPath();     // /request-demo
        String queryString = req.getQueryString();     // name=Alice&age=25
        String remoteAddr  = req.getRemoteAddr();      // Client IP
        String remoteHost  = req.getRemoteHost();      // Client hostname
        int    serverPort  = req.getServerPort();      // 8080

        // ===== Request Attributes (set by other servlets/filters) =====
        req.setAttribute("processedBy", "RequestDemoServlet");
        Object attr = req.getAttribute("processedBy");

        // ===== Session =====
        HttpSession session = req.getSession();        // Get or create session
        HttpSession existing = req.getSession(false);  // Get only if exists

        // ===== Cookies =====
        Cookie[] cookies = req.getCookies();

        // ===== Request Body (for POST) =====
        // req.getInputStream() - binary data
        // req.getReader()      - text data

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<p>Method: " + method + "</p>");
        out.println("<p>URI: " + uri + "</p>");
        out.println("<p>Name param: " + name + "</p>");
        out.println("<p>Remote IP: " + remoteAddr + "</p>");
    }
}

HttpServletResponse

HttpServletResponse Methods

HttpServletResponse Methods
@WebServlet("/response-demo")
public class ResponseDemoServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String format = req.getParameter("format");

        if ("json".equals(format)) {
            // ===== JSON Response =====
            resp.setContentType("application/json;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_OK);
            PrintWriter out = resp.getWriter();
            out.println("{\"name\":\"Alice\",\"age\":25,\"role\":\"admin\"}");

        } else if ("file".equals(format)) {
            // ===== File Download =====
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment; filename=\"data.txt\"");
            resp.getWriter().println("File content here");

        } else {
            // ===== HTML Response =====
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");

            // Set response headers
            resp.setHeader("X-Custom-Header", "MyValue");
            resp.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            resp.setIntHeader("X-Request-Count", 42);
            resp.setDateHeader("Expires", 0);

            // Set status code
            resp.setStatus(HttpServletResponse.SC_OK); // 200

            PrintWriter out = resp.getWriter();
            out.println("<h2>Response Demo</h2>");
            out.println("<p>Content-Type: " + resp.getContentType() + "</p>");
            out.println("<p>Buffer size: " + resp.getBufferSize() + "</p>");
        }
    }
}

Reading POST Body

Reading JSON POST Body

Reading JSON POST Body
@WebServlet("/api/users")
public class UserApiServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // Read JSON body from request
        StringBuilder sb = new StringBuilder();
        java.io.BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String jsonBody = sb.toString();
        // jsonBody = {"name":"Alice","email":"alice@example.com"}

        // Parse JSON (using a library like Gson or Jackson in real apps)
        // For demo: simple string parsing
        System.out.println("Received JSON: " + jsonBody);

        // Send JSON response
        resp.setContentType("application/json;charset=UTF-8");
        resp.setStatus(HttpServletResponse.SC_CREATED); // 201
        resp.getWriter().println("{\"status\":\"created\",\"message\":\"User created successfully\"}");
    }
}

Detailed Learning Notes for Servlet Request Response Objects

When studying Servlet Request Response Objects, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In Servlet, Servlet Request Response Objects becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Servlet Request Response Objects Java review example

Servlet Request Response Objects Java review example
class ServletRequestResponseObjectsReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("Servlet Request Response Objects: " + state);
    }
}

Servlet Request Response Objects guard example

Servlet Request Response Objects guard example
String value = null;
if (value == null) {
    System.out.println("Servlet Request Response Objects: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of Servlet Request Response Objects before memorizing syntax.
  • Run or trace one small Servlet example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Servlet Request Response Objects.
  • Write the rule in your own words after checking the example.
  • Connect Servlet Request Response Objects to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Servlet Request Response Objects without the situation where it is useful.
RIGHT Connect Servlet Request Response Objects to a concrete Servlet task.
Purpose makes syntax easier to recall.
WRONG Testing Servlet Request Response Objects only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Servlet Request Response Objects.
Evidence keeps debugging focused.
WRONG Memorizing Servlet Request Response Objects without the situation where it is useful.
RIGHT Connect Servlet Request Response Objects to a concrete Servlet task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Servlet Request Response Objects, then fix it and explain the fix.
  • Summarize when to use Servlet Request Response Objects and when another approach is better.
  • Write a small example that uses Servlet Request Response Objects in a realistic Servlet scenario.
  • Change one important value in the Servlet Request Response Objects example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Servlet, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.