Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Working with HttpServletRequest in Java Servlets

Tech 2

The HttpServletRequest interface represents the client's browser request. When a browser communicates with the server via HTTP, all request information gets parsed by Tomcat and encapsulated into this object. Developers can use its methods to retrieve any client request data.

1. Extracting Request Line Information

The request line contains the HTTP method, URL path, and protocol version. HttpServletRequest provides several methods to extract this information:

req.getRequestURL()   // Retrieves the complete URL from the browser request
req.getRequestURI()   // Returns the resource path portion from the request line
req.getRemoteAddr()   // Returns the client's IP address
req.getLocalAddr()    // Returns the server's IP address
req.getLocalPort()    // Returns the port number the server connector is listening on

2. Retrieving Request Headers

Request headers provide metadata about the request. You can retrieve specific header values or enumerate all headers:

// Get a specific header value by its key
String headerValue = req.getHeader("Accept");

// Get all header names as an Enumeration
Enumeration<String> headerNames = req.getHeaderNames();

Practical Example

public class RequestHandlerServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // Request line details
        System.out.println("Full URL: " + request.getRequestURL());
        System.out.println("URI: " + request.getRequestURI());
        System.out.println("Client IP: " + request.getRemoteAddr());
        System.out.println("Server IP: " + request.getLocalAddr());
        System.out.println("Server Port: " + request.getLocalPort());
        System.out.println("Server Hostname: " + request.getLocalName());
        System.out.println("Client Port: " + request.getRemotePort());
        System.out.println("Context Path: " + request.getContextPath());
        System.out.println("Protocol: " + request.getScheme());
        System.out.println("HTTP Method: " + request.getMethod());

        // Iterate through all headers
        Enumeration<String> allHeaders = request.getHeaderNames();
        while (allHeaders.hasMoreElements()) {
            String headerName = allHeaders.nextElement();
            System.out.println(headerName + ": " + request.getHeader(headerName));
        }
    }
}

3. Handling Request Data (Form Parameters)

Basic Parameter Retrieval

// Single parameter value
String value = req.getParameter("fieldName");

Multiple Values (Checkboxes)

When form elements like checkboxes can submit multiple values, use:

// Returns an array of values for parameters with multiple selections
String[] selectedOptions = req.getParameterValues("hobby");

Parameter Enumeration

// Get all parameter names
Enumeration<String> parameterNames = req.getParameterNames();

Map-Based Retrieval

// Get all parameters as a Map (key -> String[])
Map<String, String[]> allParameters = req.getParameterMap();

4. Handling Character Encoding

HTTP request data is transmitted as bytes and converted to characters by Tomcat. By default, Tomcat uses ISO-8859-1 encoding, which causes issues with non-ASCII characters like Chinese. To properly handle Chinese characters:

req.setCharacterEncoding("UTF-8");

This must be called before any getParameter() methods to take effect.

5. Complete Working Example

HTML Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Registration Form</title>
</head>
<body>
    <form method="POST" action="register">
        <table style="margin: 0 auto" width="350px" border="1">
            <tr>
                <td>Username</td>
                <td><input type="text" name="userName" value="admin"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="passWord"></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td>
                    <input type="radio" name="sex" value="male" checked> Male
                    <input type="radio" name="sex" value="female"> Female
                </td>
            </tr>
            <tr>
                <td>Interests</td>
                <td>
                    <input type="checkbox" name="interest" value="coding"> Coding
                    <input type="checkbox" name="interest" value="reading"> Reading
                    <input type="checkbox" name="interest" value="gaming"> Gaming
                </td>
            </tr>
            <tr>
                <td>Bio</td>
                <td>
                    <textarea name="description" rows="3">Software developer</textarea>
                </td>
            </tr>
            <tr>
                <td>Country</td>
                <td>
                    <select name="country">
                        <option value="us">United States</option>
                        <option value="uk">United Kingdom</option>
                        <option value="cn">China</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="Register">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Servlet Handler

package com.example.controllers;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

public class RegistrationServlet extends HttpServlet {
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // Set encoding before reading parameters
        request.setCharacterEncoding("UTF-8");
        
        // Retrieve individual form fields
        String userName = request.getParameter("userName");
        System.out.println("Username: " + userName);
        System.out.println("Password: " + request.getParameter("passWord"));
        System.out.println("Gender: " + request.getParameter("sex"));
        
        // Handle multi-select checkboxes
        String[] interests = request.getParameterValues("interest");
        System.out.println("Interests: " + Arrays.toString(interests));
        
        // Handle textarea content
        System.out.println("Bio: " + request.getParameter("description"));
        
        // Handle dropdown selection
        System.out.println("Country: " + request.getParameter("country"));
        
        System.out.println("--- All Parameters ---");
        
        // Iterate through all parameter names
        Enumeration<String> paramKeys = request.getParameterNames();
        while (paramKeys.hasMoreElements()) {
            String key = paramKeys.nextElement();
            String[] values = request.getParameterValues(key);
            System.out.println(key + ": " + Arrays.toString(values));
        }
        
        System.out.println("--- Parameter Map ---");
        
        // Alternative: work with the parameter map directly
        Map<String, String[]> paramMap = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = paramMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            System.out.println(entry.getKey() + ": " + Arrays.toString(entry.getValue()));
        }
    }
}

Important Notes on Form Elements

Element Type Submitted? Value Source
readonly Yes Current value
hidden Yes Value attribute
disabled No N/A
textarea Yes Text content between tags
select without value Yes Text content of selected option

GET vs POST Differences

Aspect GET POST
Data Location URL query string Request body
Data Types Text only Text and binary files
Data Size Limited Virtually unlimited
Security Less secure (visible in URL) More secure

Remember to call setCharacterEncoding() before accessing any parameters when dealing with international character sets.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.