Building Basic Validations in Java Servlets
Table of Contents
- 1. Introduction
- 2. What is a Java Servlet?
- 3. Validating User Input with Servlets
- 4. Step-by-Step Implementation
- Controller Class Overview
- Handling User Input in doPost
- Validation Logic with User Feedback
- 5. Example Code Walkthrough
- 6. Conclusion
Introduction
This guide explores how to implement basic validations using Java Servlets. Servlets are server-side Java programs that handle client requests and generate responses. In this article, we will walk through the process of capturing user input and validating it using servlets. This approach is essential for beginners learning how to manage form inputs, handle errors, and ensure data integrity in Java web applications.
What is a Java Servlet?
A Java Servlet is a class that extends the capabilities of servers hosting web applications. It handles client requests (like form submissions) and responds appropriately. The servlet operates under the HTTP protocol, where it can process GET and POST requests, making it ideal for handling form data.
Validating User Input with Servlets
Validation is essential in web applications to ensure the correctness of user inputs before processing. In servlets, validations can be performed directly within the doPost method, allowing real-time checks for missing fields, incorrect formats, or invalid selections. Let’s look at how to implement such validations step-by-step.
Step-by-Step Implementation
Controller Class Overview
In the provided project, the main class responsible for handling the HTTP requests is Controller.java. This servlet intercepts the POST requests, retrieves user input, and processes it.
Handling User Input in doPost
The doPost method captures data from form submissions using the HttpServletRequest object. Here, we extract details like the user’s name, gender, and selected languages:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println(request.getParameter("name") + " "); response.getWriter().println(request.getParameter("gender") + " "); PrintWriter out = response.getWriter(); String[] languages = request.getParameterValues("language"); if (languages != null) { for (String language : languages) { out.print(language); out.print(" "); } } else { out.print("None Selected "); } } |
In this example, the name, gender, and language parameters are fetched from the form. If no languages are selected, the system outputs “None Selected.”
Validation Logic with User Feedback
Basic validations can be added to ensure that users provide all required details. For example, we can check whether the user has provided their name and gender:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
String name = request.getParameter("name"); if (name == null || name.isEmpty()) { out.print("Name is required. "); } else { out.print("Name: " + name + " "); } String gender = request.getParameter("gender"); if (gender == null || gender.isEmpty()) { out.print("Gender is required. "); } else { out.print("Gender: " + gender + " "); } |
Here, if the user leaves the name or gender fields empty, the system returns an appropriate error message.
Example Code Walkthrough
Let’s dive into the main code example with basic input validation implemented.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package org.studyeasy; import jakarta.servlet.http.HttpServlet; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class Controller extends HttpServlet { private static final long serialVersionUID = 1L; public Controller() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // Name validation String name = request.getParameter("name"); if (name == null || name.isEmpty()) { out.print("Name is required. "); } else { out.print("Name: " + name + " "); } // Gender validation String gender = request.getParameter("gender"); if (gender == null || gender.isEmpty()) { out.print("Gender is required. "); } else { out.print("Gender: " + gender + " "); } // Language selection validation String[] languages = request.getParameterValues("language"); if (languages != null) { for (String language : languages) { out.print(language); out.print(" "); } } else { out.print("None Selected "); } } } |
Output Explanation
This servlet validates user input by ensuring that both the name and gender fields are filled in. If a user submits the form without these values, a message will be displayed indicating that the fields are required. The selected languages are processed and displayed if chosen; otherwise, a “None Selected” message appears.
Conclusion
Validating user input within servlets ensures that data integrity is maintained throughout the application. This article demonstrated how to build a basic validation system for user inputs like name, gender, and language selection. As you grow more familiar with servlets, you can extend this logic to handle complex validation rules and improve your web applications’ reliability.