Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Servlets · Lesson 3

Request and Response Objects

Understanding HTTP Requests and Responses

HTTP requests carry data from the client (browser) to the server, including the method (GET, POST), URL, headers, and optional body. HTTP responses return data from the server to the client: status code, headers, and body (HTML, JSON, etc.). Servlets receive request objects containing all request details and provide response objects to send replies. Mastering these is fundamental to building interactive web applications.

Parsing Request Parameters and Headers

The HttpServletRequest object provides methods to extract data from the client's request. Parameters come from query strings (?name=value) or form bodies. Headers contain metadata like User-Agent, Accept, Content-Type. Cookies are client-side storage sent with each request. Accessing these lets you personalize responses and understand client behavior.

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ParameterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // Get query parameters
        String username = request.getParameter("username");  // Single value
        String[] favoriteColors = request.getParameterValues("color");  // Multiple values
        
        // Get headers
        String userAgent = request.getHeader("User-Agent");
        String acceptLanguage = request.getHeader("Accept-Language");
        String referer = request.getHeader("Referer");
        
        // Get cookies
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        
        // Get request metadata
        String method = request.getMethod();  // "GET", "POST", etc.
        String remoteAddr = request.getRemoteAddr();
        int remotePort = request.getRemotePort();
        String serverName = request.getServerName();
        
        // Send response
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        out.println("<html><body>");
        out.println("<h1>Request Analysis</h1>");
        out.println("<p>Username: " + username + "</p>");
        out.println("<p>User Agent: " + userAgent + "</p>");
        out.println("<p>Client IP: " + remoteAddr + "</p>");
        out.println("<p>Server: " + serverName + "</p>");
        out.println("</body></html>");
    }
}

Building HTTP Responses with Status Codes and Headers

The HttpServletResponse object lets you build the reply. Set the status code to indicate success (200), redirect (301), client error (404), or server error (500). Set headers to specify content type, caching, and custom metadata. Write content to the response body using PrintWriter or ServletOutputStream.

public class ResponseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String action = request.getParameter("action");
        
        if ("success".equals(action)) {
            // 200 OK with HTML
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println("<h1>Success!</h1>");
            
        } else if ("redirect".equals(action)) {
            // 301 Moved Permanently
            response.sendRedirect("https://example.com");
            
        } else if ("error".equals(action)) {
            // 500 Internal Server Error
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Something went wrong");
            
        } else if ("json".equals(action)) {
            // JSON response
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json");
            response.getWriter().println("{\"status\": \"ok\", \"message\": \"Data received\"}");
            
        } else {
            // 404 Not Found
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Action not found");
        }
    }
}

Working with Cookies and Sessions

Cookies store small amounts of data on the client that the browser sends back with each request. Sessions store data on the server, with a session ID cookie identifying the client. Use sessions for sensitive data (logged-in user); use cookies for preferences (theme, language). Sessions are destroyed when the browser closes or a timeout occurs.

public class CookieSessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String action = request.getParameter("action");
        
        if ("login".equals(action)) {
            // Get or create session
            javax.servlet.http.HttpSession session = request.getSession(true);
            session.setAttribute("userId", 12345);
            session.setAttribute("username", "alice");
            session.setMaxInactiveInterval(30 * 60);  // 30 minutes
            
            // Also set a preference cookie
            javax.servlet.http.Cookie themeCookie = new javax.servlet.http.Cookie("theme", "dark");
            themeCookie.setMaxAge(7 * 24 * 60 * 60);  // 7 days
            response.addCookie(themeCookie);
            
            response.setContentType("text/html");
            response.getWriter().println("<h1>Logged in</h1>");
            
        } else if ("profile".equals(action)) {
            // Access session data
            javax.servlet.http.HttpSession session = request.getSession(false);
            if (session != null) {
                Integer userId = (Integer) session.getAttribute("userId");
                String username = (String) session.getAttribute("username");
                response.setContentType("text/html");
                response.getWriter().println("<h1>Welcome, " + username + "</h1>");
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not logged in");
            }
            
        } else if ("logout".equals(action)) {
            // Invalidate session
            javax.servlet.http.HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            response.sendRedirect("login.html");
        }
    }
}

Handling Form Data and File Uploads

When a form is submitted with POST, parameters come from the request body, not the URL. For file uploads, the Content-Type is multipart/form-data, and you need to parse the request carefully. Modern servlets use libraries like Apache Commons FileUpload to simplify file handling.

import javax.servlet.http.Part;

public class FormUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // Regular form fields
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        
        // File upload (requires @MultipartConfig annotation)
        Part filePart = request.getPart("file");
        String fileName = filePart.getSubmittedFileName();
        long fileSize = filePart.getSize();
        
        // Save file
        String uploadDir = getServletContext().getRealPath("/uploads");
        filePart.write(uploadDir + "/" + fileName);
        
        response.setContentType("text/html");
        response.getWriter().println("<h1>File uploaded successfully</h1>");
        response.getWriter().println("<p>File: " + fileName + " (" + fileSize + " bytes)</p>");
    }
}

// Servlet must have this annotation for file uploads:
// @WebServlet("/upload")
// @MultipartConfig
// public class FormUploadServlet extends HttpServlet { ... }

Common Response Scenarios and Status Codes

StatusMeaningUsage
200 OKSuccessNormal successful response
301/302RedirectSend client to different URL
304 Not ModifiedClient cache validDon't resend body
400 Bad RequestInvalid inputClient error in parameters
401 UnauthorizedAuthentication requiredUser must log in
403 ForbiddenAccess deniedUser lacks permission
404 Not FoundURL doesn't existResource not available
500 Internal ErrorServer errorUnexpected exception

Common Mistake: Forgetting to set Content-Type on responses. Without it, the browser doesn't know if it's receiving HTML, JSON, or binary data, leading to garbled displays or download prompts. Always set response.setContentType("text/html") or appropriate type. Also, never trust client input — validate and sanitize all parameters to prevent injection attacks.

Best Practices for Request/Response Handling

  • Always set Content-Type on responses before writing output
  • Validate all input from request parameters and headers
  • Use request.getParameter() for simple values; parse JSON for complex data
  • Set appropriate status codes: don't always return 200 OK
  • Use sessions for authentication state, cookies for non-sensitive preferences
  • Implement CSRF protection: use tokens for state-changing operations (POST, DELETE)
  • Add security headers: X-Frame-Options, Content-Security-Policy, etc.
  • Log requests for debugging: URL, parameters, user, timestamp

Real-World Example: User Registration Form

A servlet at /register displays a registration form on GET. On POST, it extracts username, email, and password parameters, validates them (non-empty, email format, strong password), saves to the database, sets a session cookie, and redirects to the dashboard. If validation fails, it returns 400 with error messages. If the username already exists, it returns 409 (Conflict). By carefully handling requests and responses, the servlet provides a secure, user-friendly registration flow.

Quiz Check

Quick Knowledge Test

Loading quiz questions...