Retrieving Form Data and Request Parameters in Java Servlets
Course: Advanced Java Training
Topic: Retrieving Form Data and Request Parameters
Course Link: Advanced Java Training Course
Demo Link: Register for a Free Course Demo
Website: JustAcademy
1. Introduction to Retrieving Form Data and Request Parameters
In Java web applications, HTML forms allow users to submit information such as usernames, passwords, email addresses, search terms, and registration details. Java Servlets process these submissions on the server side by accessing request data through the HttpServletRequest interface.
Retrieving form data is an essential part of server-side application development. It enables a servlet to receive user input, validate submitted values, perform business logic, communicate with databases, and generate appropriate responses.
For example, when a user submits a registration form, the servlet can retrieve the name and email address, validate the values, save the information to a database, and display a confirmation message.
2. Learning Objectives
- Understand HTML forms and HTTP form submissions.
- Learn the role of the
HttpServletRequest interface.
- Retrieve individual form fields using
getParameter().
- Understand the difference between request parameters and request attributes.
- Retrieve multiple values using
getParameterValues().
- Access all submitted parameter names using
getParameterNames().
- Work with GET and POST form submissions.
- Validate and safely process user input.
- Handle missing parameters and incorrect input.
3. Understanding HTML Forms
An HTML form collects information from users and sends it to a server endpoint. The action attribute specifies the destination, while the method attribute determines how the form data is submitted.
Example: HTML Registration Form
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>User Registration</h2>
<form action="register" method="post">
<label for="name">Full Name:</label>
<input type="text" id="name" name="fullName" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="1">
<br><br>
<button type="submit">Register</button>
</form>
</body>
</html>
Explanation
action="register" sends the form submission to the servlet mapped to the /register URL relative to the current application path.
method="post" submits the form data in the HTTP request body.
name="fullName" defines the parameter name that the servlet uses to retrieve the submitted name.
name="email" identifies the email request parameter.
required provides browser-side validation, but server-side validation is still necessary.
Important: The HTML name attribute determines the request parameter name. The id attribute is primarily used to identify an element in the document and associate labels with inputs.
4. Understanding HttpServletRequest
HttpServletRequest is an interface in the Servlet API that represents an incoming HTTP request. A servlet container, such as Apache Tomcat, provides the request object when processing a request.
The servlet uses this object to access submitted form values, query parameters, HTTP headers, cookies, request metadata, and other information associated with the request.
Common Methods of HttpServletRequest
| Method |
Purpose |
Example |
getParameter(String name) |
Retrieves one parameter value. |
request.getParameter("email") |
getParameterValues(String name) |
Retrieves all values for a parameter. |
request.getParameterValues("skills") |
getParameterNames() |
Returns an enumeration of parameter names. |
request.getParameterNames() |
getParameterMap() |
Returns a map of parameter names to their values. |
request.getParameterMap() |
getMethod() |
Returns the HTTP method. |
request.getMethod() |
getQueryString() |
Returns the raw URL query string, if present. |
request.getQueryString() |
getHeader(String name) |
Retrieves an HTTP header. |
request.getHeader("User-Agent") |
getAttribute(String name) |
Retrieves a server-side request attribute. |
request.getAttribute("message") |
5. Retrieving a Single Form Parameter Using getParameter()
The getParameter() method is the most frequently used method for retrieving HTML form data. It accepts a parameter name and returns the corresponding value as a String.
Syntax
String value = request.getParameter("parameterName");
Example: Retrieving a Username
String username = request.getParameter("username");
If the submitted form contains a field named username with the value Rahul, the method returns the string "Rahul".
If the parameter is missing, getParameter() returns null. If the parameter exists but has an empty value, the returned string may be empty.
6. Complete Example: Processing Form Data in a Servlet
HTML Form
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login</h2>
<form action="login" method="post">
<label>Username:</label>
<input type="text" name="username" required>
<br><br>
<label>Email:</label>
<input type="email" name="email" required>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Java Servlet
The following example uses the modern jakarta.servlet package, suitable for Jakarta Servlet-based containers such as Tomcat 10 and later.
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String email = request.getParameter("email");
response.setCharacterEncoding("UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html><body>");
out.println("<h2>Form Submitted</h2>");
if (username == null || username.isBlank()
|| email == null || email.isBlank()) {
out.println("<p>Please provide all required fields.</p>");
} else {
out.println("<p>Username: "
+ escapeHtml(username) + "</p>");
out.println("<p>Email: "
+ escapeHtml(email) + "</p>");
}
out.println("</body></html>");
}
}
private String escapeHtml(String value) {
return value.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(""", """)
.replace("'", "'");
}
}
How the Program Works
- The user enters a username and email address in the HTML form.
- The browser submits the form using the HTTP POST method.
- The servlet container maps the request to
LoginServlet.
- The
doPost() method receives the request and response objects.
- The servlet retrieves the form fields using
getParameter().
- The servlet checks whether the submitted values are missing or blank.
- The output is HTML-escaped before user-controlled values are written into the response.
- The servlet returns the generated HTML response to the browser.
Note: HTML escaping helps prevent cross-site scripting when displaying user-controlled text in an HTML text context. Different output contexts require appropriate encoding. For projects using older Java EE containers, imports may use javax.servlet instead of jakarta.servlet.
7. Understanding GET and POST Parameters
Servlet request parameters can come from query strings in URLs or form submissions. The getParameter() method can retrieve parameters from both sources when the servlet container parses them.
| Feature |
GET |
POST |
| Typical use |
Search, filters, and retrieving resources. |
Submitting forms and creating or updating data. |
| Parameter location |
Usually in the URL query string. |
Commonly in the request body for standard form submissions. |
| Visibility |
Parameters appear in the URL. |
Form body values are not normally displayed in the URL. |
| Bookmarking |
Suitable for shareable, repeatable URLs. |
Not generally suitable for bookmarking submitted form bodies. |
| Security |
HTTPS is important when transmitting sensitive data. |
HTTPS is also required for protecting sensitive data in transit. |
Important: POST does not automatically encrypt data or make it secure. Use HTTPS, validate all inputs, and apply suitable authentication and authorization controls. Passwords and other sensitive information should not be placed in query strings.
Example: GET Request
http://localhost:8080/MyApp/search?keyword=Java&category=training
String keyword = request.getParameter("keyword");
String category = request.getParameter("category");
Example: POST Request
<form action="register" method="post">
<input type="text" name="fullName">
<input type="email" name="email">
<button type="submit">Register</button>
</form>
String fullName = request.getParameter("fullName");
String email = request.getParameter("email");
8. Retrieving Multiple Values Using getParameterValues()
Some HTML form controls allow users to select multiple values. For example, checkboxes can represent multiple skills, hobbies, interests, or preferred technologies.
The getParameterValues() method returns a String[] containing the submitted values for the specified parameter name. It returns null when the parameter is not present.
HTML Example
<form action="skills" method="post">
<label>
<input type="checkbox" name="skills" value="Java">
Java
</label>
<label>
<input type="checkbox" name="skills" value="SQL">
SQL
</label>
<label>
<input type="checkbox" name="skills" value="Servlets">
Servlets
</label>
<button type="submit">Submit Skills</button>
</form>
Servlet Example
String[] skills = request.getParameterValues("skills");
if (skills != null) {
for (String skill : skills) {
System.out.println(skill);
}
} else {
System.out.println("No skills selected.");
}
Possible Output
Java
SQL
Servlets
If a user selects Java and SQL, the array contains those two values. If no checkbox is selected, the parameter may be absent and the method returns null.
9. Retrieving Parameter Names Using getParameterNames()
The getParameterNames() method returns an Enumeration of the parameter names available in the request. This can be useful when processing forms with a dynamic set of fields.
Example
import java.util.Enumeration;
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = request.getParameter(name);
System.out.println(name + " = " + value);
}
This example prints each parameter name and its first value. For parameters that can contain multiple values, use getParameterValues() when all values are needed.
Do not rely on request parameter ordering. Also, avoid logging passwords, authentication tokens, or other sensitive submitted information.
10. Retrieving All Parameters Using getParameterMap()
The getParameterMap() method returns a map where each key is a parameter name and each value is an array of strings. It is useful when a servlet needs to examine all submitted parameters.
Example
import java.util.Map;
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry
: parameters.entrySet()) {
String parameterName = entry.getKey();
String[] values = entry.getValue();
System.out.println("Parameter: " + parameterName);
for (String value : values) {
System.out.println("Value: " + value);
}
}
The returned parameter map should be treated as read-only. To change submitted values for application logic, create a separate application-level data structure instead of attempting to modify the request parameter map.
11. Request Parameters vs. Request Attributes
Request parameters and request attributes are different concepts in the Servlet API.
| Feature |
Request Parameters |
Request Attributes |
| Origin |
Submitted by the client through a query string or form. |
Usually created or set by server-side code. |
| Data access |
getParameter() |
getAttribute() |
| Setting data |
Values come from the request submission. |
setAttribute() |
| Typical data type |
Strings or arrays of strings. |
Any Java object. |
| Common purpose |
Reading user input. |
Passing server-side data to a JSP or another component. |
Example: Setting a Request Attribute
String username = request.getParameter("username");
request.setAttribute("welcomeMessage",
"Welcome, " + username);
request.getRequestDispatcher("/welcome.jsp")
.forward(request, response);
Retrieving the Attribute in JSP
${welcomeMessage}
In this example, username is a client-submitted parameter, while welcomeMessage is a server-side request attribute. A request attribute is not automatically sent to the browser as a form parameter.
12. Handling Missing and Empty Parameters
Form fields may be missing, blank, or contain invalid values. Servlets should check user input before using it in business logic or database operations.
Example
String email = request.getParameter("email");
if (email == null) {
System.out.println("Email parameter is missing.");
} else if (email.isBlank()) {
System.out.println("Email cannot be empty.");
} else {
System.out.println("Email received.");
}
These checks distinguish a missing parameter from a submitted blank value. They do not prove that an email address is valid. Apply suitable validation rules before processing the input.
13. Converting Request Parameters into Other Data Types
Request parameters are returned as strings. When an application requires numeric values, dates, or other data types, the servlet must parse and validate the input.
Example: Reading an Age
String ageValue = request.getParameter("age");
if (ageValue == null || ageValue.isBlank()) {
System.out.println("Age is required.");
} else {
try {
int age = Integer.parseInt(ageValue);
if (age < 1 || age > 120) {
System.out.println("Age is outside the allowed range.");
} else {
System.out.println("Age: " + age);
}
} catch (NumberFormatException e) {
System.out.println("Please enter a valid whole number.");
}
}
Explanation: Integer.parseInt() converts a numeric string into an integer. If the submitted value contains non-numeric characters or falls outside the integer range, it throws NumberFormatException. Range validation is a separate step.
14. Character Encoding and International Text
Forms may contain names and text in different languages. Correct character encoding helps prevent submitted characters from becoming corrupted.
For POST form data, set the request character encoding before reading request parameters.
request.setCharacterEncoding("UTF-8");
String fullName = request.getParameter("fullName");
For GET query parameters, decoding behavior depends on the servlet container and its connector configuration. Configure UTF-8 consistently for the application and server. Setting the request encoding after parameters have already been read may not change values that the container has already parsed.
15. Validating Form Data on the Server
Client-side HTML validation improves the user experience, but it cannot replace server-side validation. A client can disable browser validation or submit a crafted HTTP request directly.
Important Validation Checks
- Required fields: Verify that mandatory parameters exist and are not blank.
- Length limits: Reject values that exceed the application's allowed size.
- Format validation: Validate emails, phone numbers, dates, and other structured data.
- Range validation: Check numeric values against acceptable minimum and maximum limits.
- Business rules: Verify that the submitted values are valid for the requested operation.
- Authorization: Ensure the current user has permission to perform the requested action.
- Database safety: Use prepared statements when including input in SQL queries.
- Output encoding: Encode user-controlled values correctly before displaying them in HTML.
16. Using Form Parameters with JDBC
A common enterprise Java workflow involves collecting form data, validating it in a servlet, and saving it to a relational database through JDBC. User input should never be directly concatenated into SQL statements.
Example: PreparedStatement
String username = request.getParameter("username");
String email = request.getParameter("email");
if (username == null || username.isBlank()
|| email == null || email.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Username and email are required.");
return;
}
String sql = "INSERT INTO users (username, email) VALUES (?, ?)";
try (java.sql.Connection connection =
dataSource.getConnection();
java.sql.PreparedStatement statement =
connection.prepareStatement(sql)) {
statement.setString(1, username);
statement.setString(2, email);
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
response.getWriter().println("Registration successful.");
}
}
This example assumes that a configured DataSource is available in the application and that the database schema matches the query. In production applications, handle database exceptions, enforce database constraints, and avoid exposing internal error details to users.
17. Common Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
getParameter() returns null. |
The field name is incorrect or the parameter was not submitted. |
Verify the HTML name attribute and inspect the request. |
| Values are empty. |
The user submitted a blank field. |
Check for null and blank values. |
| Servlet returns 404. |
The servlet mapping or form action is incorrect. |
Verify @WebServlet, the deployment context, and the form URL. |
| NumberFormatException occurs. |
A submitted value cannot be parsed as a number. |
Validate and parse inside a suitable exception-handling block. |
| Multiple selections are missing. |
The code uses getParameter() instead of retrieving all values. |
Use getParameterValues(). |
| Characters display incorrectly. |
Encoding configuration is inconsistent. |
Configure UTF-8 and set request encoding before reading parameters. |
Form values are not processed in doPost(). |
The form submits using GET or targets the wrong URL. |
Match the form method to the servlet handler and verify its mapping. |
| SQL errors occur. |
Input types, database schema, or SQL execution may be incorrect. |
Validate data, check the schema, and use prepared statements. |
18. Best Practices for Retrieving Request Parameters
- Use meaningful parameter names that match the HTML form's
name attributes.
- Validate every client-submitted value on the server.
- Check for null and blank values before processing.
- Use
getParameterValues() for multi-valued form fields.
- Set request character encoding before reading POST parameters.
- Use prepared statements for database operations.
- Escape user-controlled output to prevent cross-site scripting.
- Never treat client-side validation as a security boundary.
- Avoid logging passwords, session identifiers, and sensitive personal information.
- Use HTTPS to protect data in transit.
- Use POST for appropriate state-changing operations and implement CSRF protection where applicable.
- Separate request handling, business logic, and database access as applications grow.
19. Practical Exercises
Exercise 1: Student Registration
Create an HTML form that accepts a student's name, email, and course. Retrieve each value in a servlet using getParameter() and display a confirmation page.
Exercise 2: Employee Details
Create a form that accepts an employee ID, name, and salary. Parse the salary as a numeric value, validate it, and display an appropriate result.
Exercise 3: Multiple Skills Selection
Create checkboxes for Java, SQL, HTML, CSS, and JavaScript. Use getParameterValues() to retrieve and display all selected skills.
Exercise 4: Search Application
Create a GET form that accepts a keyword and category. Retrieve both parameters and display the search criteria on the result page.
Exercise 5: Database Registration
Build a registration form that validates user input and inserts records into a database using JDBC and PreparedStatement.
20. Interview Questions and Answers
Q1. What is HttpServletRequest?
Answer: It is a Servlet API interface representing an incoming HTTP request. It provides methods to access request parameters, headers, attributes, and other request information.
Q2. What does getParameter() do?
Answer: It retrieves the first value associated with a specified request parameter and returns it as a string. It returns null if the parameter is absent.
Q3. What is the difference between getParameter() and getParameterValues()?
Answer: getParameter() returns one string value, while getParameterValues() returns an array containing all values associated with a parameter.
Q4. Can getParameter() read GET and POST data?
Answer: Yes. It can retrieve query parameters and parsed form parameters from supported request content types. The exact parsing behavior depends on the request and servlet container configuration.
Q5. Why does getParameter() return null?
Answer: The parameter may be absent, the HTML field name may not match, or the request may not contain the expected data.
Q6. What is the difference between a request parameter and a request attribute?
Answer: A parameter represents client-submitted request data, while an attribute is an object stored in the request by server-side application code.
Q7. Why is server-side validation necessary?
Answer: Client-side validation can be bypassed. Server-side validation helps enforce application rules and prevents invalid data from being processed.
Q8. How can form data be stored safely in a database?
Answer: Validate the submitted data, use JDBC with a PreparedStatement, handle database errors appropriately, and enforce database constraints.
Q9. What is getParameterMap()?
Answer: It returns a map of request parameter names to arrays of submitted string values.
Q10. How should a servlet handle numeric input?
Answer: Check for missing or blank input, parse it with an appropriate conversion method, handle parsing exceptions, and validate the permitted range.
21. Quick Revision
HttpServletRequest provides access to incoming HTTP request data.
getParameter("name") retrieves a single parameter value.
getParameterValues("name") retrieves multiple values.
getParameterNames() enumerates parameter names.
getParameterMap() provides a map of all parameter values.
- Request parameters are client-submitted data; request attributes are server-side objects.
- GET parameters commonly appear in the URL, while POST form data is commonly sent in the request body.
- All input must be validated on the server.
- Use prepared statements for SQL queries and proper output encoding for HTML.
- Configure character encoding before reading request parameters.
22. Conclusion
Retrieving form data and request parameters is a fundamental skill in Java Servlet development. The HttpServletRequest interface enables applications to read user-submitted values, process form submissions, validate input, and pass data to business logic or database layers.
By mastering getParameter(), getParameterValues(), getParameterNames(), and getParameterMap(), developers can build reliable form-processing workflows. Combining these methods with server-side validation, secure database access, correct character encoding, and appropriate output encoding helps create maintainable and secure Java web applications.
Learn Advanced Java with JustAcademy
Strengthen your understanding of Java Servlets, HTTP requests and responses, form processing, JDBC, JSP, and enterprise web application development through structured learning and practical exercises.
Explore the Advanced Java Training Course
Register for a Course Demo
Visit the JustAcademy Website