Lecture 25: Handling HTTP GET & POST Requests

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-13

Lecture 25

Handling HTTP GET & POST Requests

Week 8 | Unit III: Servlets
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Understand HTTP request methods (GET, POST, PUT, DELETE)
  • Differentiate between GET and POST requests
  • Implement doGet() and doPost() methods
  • Handle HTML form submissions with proper parameters
  • Extract request parameters and handle multiple values
  • Send appropriate HTTP responses with proper status codes
  • Apply input validation and error handling
  • Use POST-Redirect-GET pattern to prevent duplicate submissions
  • Apply security best practices for sensitive data

HTTP Request Methods


Common HTTP Methods:

  • GET: Retrieve data from server
  • POST: Send data to server
  • PUT: Update existing resource
  • DELETE: Remove resource
  • HEAD: Get headers only
  • OPTIONS: Get supported methods

In servlets, we primarily use GET and POST.

HTTP Request-Response Cycle


sequenceDiagram
    participant B as Browser
    participant S as Servlet
    participant D as Database
    
    B->>S: HTTP Request (GET/POST)
    S->>D: Query Data
    D-->>S: Return Data
    S-->>B: HTTP Response

GET Method: Retrieving Data


Purpose: Request data from server

Characteristics:

  • Data sent in URL query string
  • Limited data size (~2KB)
  • Visible in browser address bar
  • Can be bookmarked
  • Can be cached
  • Not secure for sensitive data
  • Idempotent (same result on repeated calls)

GET Request Example


URL with Query Parameters:

http://localhost:8080/app/search?query=java&category=books

HTML Form (GET):

<form action="search" method="GET">
  <input type="text" name="query" placeholder="Search term">
  <input type="text" name="category" value="books">
  <button type="submit">Search</button>
</form>

Handling GET Requests: doGet()


@WebServlet("/search")
public class SearchServlet extends HttpServlet {
  
  protected void doGet(HttpServletRequest request,
                     HttpServletResponse response)
    throws ServletException, IOException {
 
    // Get query parameters from URL
    String query = request.getParameter("query");
    String category = request.getParameter("category");
    
    // Generate response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<h1>Search Results</h1>");
    out.println("<p>Query: " + query + "</p>");
    out.println("<p>Category: " + category + "</p>");
    out.close();
  }
}

When to Use GET


  • Search operations: Searching products, articles
  • Filtering data: Sort, filter options
  • Pagination: Page numbers in URL
  • Sharing links: Bookmarkable URLs
  • Read-only operations: No data modification
  • Public data: Non-sensitive information

Example URLs:

/products?category=electronics&sort=price
/articles?page=2&limit=10
/weather?city=Mumbai&units=metric

POST Method: Submitting Data


Purpose: Submit data to server

Characteristics:

  • Data sent in request body (hidden)
  • Unlimited data size
  • Not visible in URL
  • Cannot be bookmarked
  • Not cached
  • More secure than GET
  • Non-idempotent (may have different results)

POST Request Example


HTML Form (POST):

<form action="register" method="POST">
  <input type="text" name="username" required>
  <input type="email" name="email" required>
  <input type="password" name="password" required>
  <input type="date" name="dob">
  <button type="submit">Register</button>
</form>

Form data sent in request body, not visible in URL.

Handling POST Requests: doPost()


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
  
  protected void doPost(HttpServletRequest request,
                       HttpServletResponse response)
    throws ServletException, IOException {
    
    // Get form parameters from request body
    String username = request.getParameter("username");
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String dob = request.getParameter("dob");
    
    // Process registration (save to database)
    boolean success = saveUser(username, email, password, dob);
    
    // Send response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (success) {
      out.println("<h1>Registration Successful!</h1>");
      out.println("<p>Welcome, " + username + "</p>");
    } else {
      out.println("<h1>Registration Failed</h1>");
    }
  }
  
  private boolean saveUser(String username, String email, 
                          String password, String dob) {
    // Database logic here
    return true;
  }
}

When to Use POST


  • User registration: Creating new accounts
  • Login forms: Authenticating users
  • Data submission: Creating/updating records
  • File uploads: Sending files to server
  • Sensitive data: Passwords, credit cards
  • Large data: No size limitations

Examples: - User registration and login - Contact form submission - Blog post creation - Order placement

GET vs POST Comparison


Feature GET POST
Data Location URL query string Request body
Visibility Visible in URL Hidden
Data Size Limited (~2KB) Unlimited
Security Less secure More secure
Bookmarking Can bookmark Cannot bookmark
Caching Can be cached Not cached
Browser History Saved Not saved
Use Case Retrieve data Submit data
Idempotent Yes No

Extracting Request Parameters


// Single parameter value
String name = request.getParameter("name");

// Multiple values for same parameter (checkboxes)
String[] hobbies = request.getParameterValues("hobby");

// All parameter names
Enumeration<String> paramNames = request.getParameterNames();

// All parameters as Map
Map<String, String[]> paramMap = request.getParameterMap();
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
  System.out.println(entry.getKey() + ": " + 
                    Arrays.toString(entry.getValue()));
}

Handling Multiple Values (Checkboxes)


HTML Form:

<form action="preferences" method="POST">
  <input type="checkbox" name="hobby" value="coding"> Coding
  <input type="checkbox" name="hobby" value="music"> Music
  <input type="checkbox" name="hobby" value="sports"> Sports
  <button type="submit">Submit</button>
</form>

Servlet:

protected void doPost(...) {
  String[] hobbies = request.getParameterValues("hobby");
  if (hobbies != null) {
    for (String hobby : hobbies) {
      System.out.println("Hobby: " + hobby);
    }
  }
}

Request Information Methods


// HTTP method (GET, POST, etc.)
String method = request.getMethod();

// Request URI
String uri = request.getRequestURI();  // /app/login

// Query string (for GET)
String query = request.getQueryString();  // user=john&id=5

// Request URL
StringBuffer url = request.getRequestURL();

// Context path
String contextPath = request.getContextPath();  // /app

// Servlet path
String servletPath = request.getServletPath();  // /login

Response Methods


// Set content type
response.setContentType("text/html; charset=UTF-8");

// Get writer for text output
PrintWriter out = response.getWriter();

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

// Redirect to another page
response.sendRedirect("success.html");

Common Content Types


// HTML page
response.setContentType("text/html");

// Plain text
response.setContentType("text/plain");

// JSON data
response.setContentType("application/json");

// XML data
response.setContentType("application/xml");

// PDF file
response.setContentType("application/pdf");

Complete Login Example


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
  
  protected void doPost(HttpServletRequest request,
                       HttpServletResponse response)
    throws ServletException, IOException {
    
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
    // Validate credentials
    if (authenticate(username, password)) {
      // Success - redirect to home
      HttpSession session = request.getSession();
      session.setAttribute("user", username);
      response.sendRedirect("home.jsp");
    } else {
      // Failure - show error
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<h1>Login Failed!</h1>");
      out.println("<a href='login.html'>Try Again</a>");
    }
  }
  
  private boolean authenticate(String user, String pass) {
    // Database authentication logic
    return "admin".equals(user) && "password".equals(pass);
  }
}

Handling Both GET and POST


@WebServlet("/user")
public class UserServlet extends HttpServlet {
  
  // Show user form (GET)
  protected void doGet(HttpServletRequest request,
                     HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    // Display form
  }
  
  // Process form submission (POST)
  protected void doPost(HttpServletRequest request,
                       HttpServletResponse response)
    throws ServletException, IOException {
    // Process form data
  }
}

POST-Redirect-GET Pattern


sequenceDiagram
    participant Browser
    participant Servlet
    
    Browser->>Servlet: POST /register (form data)
    Servlet->>Servlet: Process & Save Data
    Servlet-->>Browser: 302 Redirect to /success
    Browser->>Servlet: GET /success
    Servlet-->>Browser: 200 Success Page

Benefits: - Prevents duplicate submissions on page refresh - Cleaner browser history - Better user experience

Calculator Example


HTML Form:

<form action="calculate" method="POST">
  <input type="number" name="num1" required>
  <select name="operation">
    <option value="add">+</option>
    <option value="subtract">-</option>
  </select>
  <input type="number" name="num2" required>
  <button type="submit">Calculate</button>
</form>

Calculator Servlet


@WebServlet("/calculate")
public class CalculatorServlet extends HttpServlet {
  
  protected void doPost(HttpServletRequest request,
                       HttpServletResponse response)
    throws ServletException, IOException {
    
    int num1 = Integer.parseInt(request.getParameter("num1"));
    int num2 = Integer.parseInt(request.getParameter("num2"));
    String operation = request.getParameter("operation");
    
    int result = 0;
    switch(operation) {
      case "add": result = num1 + num2; break;
      case "subtract": result = num1 - num2; break;
      case "multiply": result = num1 * num2; break;
      case "divide": result = num1 / num2; break;
    }
    
    response.setContentType("text/html");
    response.getWriter().println("<h1>Result: " + result + "</h1>");
  }
}

HTTP Status Codes


Success (2xx)

  • 200 OK - Request successful
  • 201 Created - Resource created

Redirection (3xx)

  • 301 Moved Permanently
  • 302 Found (Temporary redirect)

Client Error (4xx)

  • 400 Bad Request
  • 404 Not Found
  • 403 Forbidden

Server Error (5xx)

  • 500 Internal Server Error
  • 503 Service Unavailable

Error Handling


protected void doPost(HttpServletRequest request,
                     HttpServletResponse response)
  throws ServletException, IOException
{
  
  try {
    String age = request.getParameter("age");
    int ageValue = Integer.parseInt(age);
    // Process age
  } catch (NumberFormatException e) {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    PrintWriter out = response.getWriter();
    out.println("Invalid age format!");
  } catch (Exception e) {
    response.sendError(500, "Internal Server Error");
  }
}

Input Validation Example


// Validate required parameters
if (username == null || username.trim().isEmpty()) {
  response.sendError(400, "Username is required");
  return;
}

// Validate format (email)
if (!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
  response.sendError(400, "Invalid email format");
  return;
}

// Validate length
if (password.length() < 8) {
  response.sendError(400, "Password must be at least 8 characters");
  return;
}

Security Best Practices


  • Use POST for sensitive data (passwords, personal info)
  • Validate and sanitize all input
  • Use HTTPS for production
  • Protect against SQL injection
  • Implement CSRF tokens for forms
  • Encode output to prevent XSS attacks
  • Use parameterized queries
  • Never trust client-side validation alone

Complete Form to Servlet Flow


registration.html:

<form action="register" method="POST">
  <input type="text" name="username" required>
  <input type="email" name="email" required>
  <input type="password" name="password" required>
  <button type="submit">Register</button>
</form>

RegisterServlet.java:

protected void doPost(...) {
  // Extract form data
  String username = request.getParameter("username");
  String email = request.getParameter("email");
  String password = request.getParameter("password");
  // Process and respond
  response.sendRedirect("welcome.jsp");
}

Common Mistakes to Avoid


  • Using GET for sensitive data
  • Not validating input parameters
  • Forgetting to set content type
  • Not handling null parameters
  • Hardcoding URLs in redirects
  • Ignoring character encoding
  • Not closing PrintWriter
  • Mixing HTML and Java code excessively

Summary


  • GET retrieves data, POST submits data
  • GET: data in URL, POST: data in body
  • Use doGet() for GET requests
  • Use doPost() for POST requests
  • Extract parameters using request.getParameter()
  • Set content type before writing response
  • Validate all user input
  • Use POST for sensitive/large data
  • Apply POST-Redirect-GET pattern for better UX
  • Always prioritize security in your servlets

Practice Exercise


Create a Student Search & Registration System:

  1. HTML form with search (GET) and registration (POST) capabilities
  2. Servlet to handle both GET (search/filter) and POST (registration)
  3. Validate all form inputs (email format, password strength)
  4. Display search results with pagination
  5. Show confirmation page after registration
  6. Use POST-Redirect-GET pattern for registration
  7. Set appropriate HTTP status codes for success/failure

Bonus: Implement input sanitization and security checks

Resources & References


Questions?

Next: Lecture 26 - Redirecting Requests & Request Dispatching