Fetch Form Data with Java Servlet
This tutorial guides you through creating a Java Servlet application that collects form data from an HTML page, processes it using a Servlet, and displays the data on another JSP page. We’ll use Apache Tomcat as the server and Eclipse IDE for development. Every step is explained in detail for beginners.
Prerequisites
- Java Development Kit (JDK): JDK 8 or higher installed.
- Eclipse IDE: Eclipse IDE for Enterprise Java Developers.
- Apache Tomcat: Version 9 or 10 (we’ll use Tomcat 10 in this tutorial).
- Basic Knowledge: Familiarity with HTML, Java, and basic web concepts.
Step 1: Set Up Your Development Environment
- Install JDK:
- Download and install JDK from Oracle’s website.
- Set the
JAVA_HOME
environment variable to the JDK installation path (e.g.,C:\Program Files\Java\jdk-11
). - Add
%JAVA_HOME%\bin
to your system’sPATH
variable.
- Install Eclipse IDE:
- Download Eclipse IDE for Enterprise Java Developers from eclipse.org.
- Install and launch Eclipse.
- Install Apache Tomcat:
- Download Tomcat 10 from tomcat.apache.org.
- Extract the downloaded file to a directory (e.g.,
C:\apache-tomcat-10
). - In Eclipse, go to
Window > Preferences > Server > Runtime Environments
. - Click
Add
, selectApache Tomcat v10.0
, and point to the extracted Tomcat directory.
- Create a Dynamic Web Project:
- In Eclipse, go to
File > New > Dynamic Web Project
. - Name the project
FormDataServletDemo
. - Set the target runtime to
Apache Tomcat v10.0
. - Ensure the Dynamic Web Module version is 5.0 (for Servlet 5.0).
- Click
Finish
.
- In Eclipse, go to
Step 2: Create the HTML Form
We’ll create an HTML page (index.html
) with a form to collect user input (name and email).
- Create the HTML File:
- In the Project Explorer, navigate to
FormDataServletDemo > src > main > webapp
. - Right-click on
webapp
, selectNew > HTML File
. - Name it
index.html
and clickOK
.
- In the Project Explorer, navigate to
- Write the HTML Code:
- Replace the content of
index.html
with the following:
- Replace the content of
<!DOCTYPE html>
<html>
<head>
<title>User Input Form</title>
</head>
<body>
<h2>User Information Form</h2>
<form action="ProcessFormServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="userName" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="userEmail" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
- The
<form>
tag specifies:action="ProcessFormServlet"
: The URL pattern of the Servlet that will process the form.method="post"
: Uses POST to securely send form data.
- Input fields
userName
anduserEmail
collect the name and email. - The
required
attribute ensures the fields are not empty.
Step 3: Create the Servlet
We’ll create a Servlet (ProcessFormServlet
) to fetch and process the form data.
- Create the Servlet:
- In
FormDataServletDemo > src > main > java
, right-click and selectNew > Package
. - Name the package
com.example
. - Right-click on the
com.example
package, selectNew > Servlet
. - Name the Servlet
ProcessFormServlet
. - Click
Finish
.
- In
- Modify the Servlet Code:
- Eclipse generates a template for
ProcessFormServlet.java
. Replace its content with:
- Eclipse generates a template for
package com.example;
import java.io.IOException;
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("/ProcessFormServlet")
public class ProcessFormServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Fetch form data
String name = request.getParameter("userName");
String email = request.getParameter("userEmail");
// Store data in request attributes to pass to JSP
request.setAttribute("name", name);
request.setAttribute("email", email);
// Forward to the result JSP page
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Explanation:
@WebServlet("/ProcessFormServlet")
: Maps the Servlet to the URL/ProcessFormServlet
, matching the form’saction
.doPost
: Handles POST requests from the form.request.getParameter
: Retrieves form data by field name (userName
,userEmail
).request.setAttribute
: Stores data to pass to the JSP page.request.getRequestDispatcher
: Forwards the request toresult.jsp
.
Step 4: Create the Result JSP Page
We’ll create a JSP page (result.jsp
) to display the form data.
- Create the JSP File:
- In
FormDataServletDemo > src > main > webapp
, right-click and selectNew > JSP File
. - Name it
result.jsp
and clickOK
.
- In
- Write the JSP Code:
- Replace the content of
result.jsp
with:
- Replace the content of
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Form Submission Result</title>
</head>
<body>
<h2>Submitted Information</h2>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
<a href="index.html">Back to Form</a>
</body>
</html>
Explanation:
${name}
and${email}
: EL (Expression Language) retrieves the attributes set in the Servlet.- The page displays the submitted name and email.
- A link allows the user to return to the form.
Step 5: Configure the Web Deployment Descriptor
The web.xml
file maps Servlets to URLs. Since we used the @WebServlet
annotation, we don’t need to modify web.xml
manually. However, let’s verify its setup.
- Check web.xml:
- Open
FormDataServletDemo > src > main > webapp > WEB-INF > web.xml
. - Ensure it has the following (Eclipse generates this for Dynamic Web Module 5.0):
- Open
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<display-name>FormDataServletDemo</display-name>
</web-app>
Note: If you didn’t use @WebServlet
, you would need to add a <servlet>
and <servlet-mapping>
in web.xml
. The annotation simplifies this.
Step 6: Run the Application
- Add the Project to Tomcat:
- In Eclipse, go to the
Servers
view (if not visible, enable it viaWindow > Show View > Servers
). - Right-click on
Tomcat v10.0 Server
, selectAdd and Remove
. - Add
FormDataServletDemo
to theConfigured
list and clickFinish
.
- In Eclipse, go to the
- Start the Server:
- Right-click on the Tomcat server in the
Servers
view and selectStart
.
- Right-click on the Tomcat server in the
- Access the Application:
- Open a browser and navigate to
http://localhost:8080/FormDataServletDemo/index.html
. - You should see the form. Enter a name and email, then click
Submit
. - The
result.jsp
page should display the submitted data.
- Open a browser and navigate to
Step 7: Test the Application
- Test Valid Input:
- Enter a name (e.g., “John Doe”) and a valid email (e.g., “john@example.com“).
- Submit the form and verify that
result.jsp
displays the correct name and email.
- Test Empty Fields:
- Try submitting the form without entering data. The
required
attribute in the HTML should prevent submission.
- Try submitting the form without entering data. The
- Test Navigation:
- Click the “Back to Form” link on
result.jsp
to ensure it returns toindex.html
.
- Click the “Back to Form” link on
Step 8: Debugging Tips
If the application doesn’t work:
- Check Tomcat Logs:
- View logs in Eclipse’s
Console
view or inC:\apache-tomcat-10\logs
.
- View logs in Eclipse’s
- Verify URL:
- Ensure you’re accessing
http://localhost:8080/FormDataServletDemo/index.html
.
- Ensure you’re accessing
- Check Servlet Mapping:
- Confirm the
@WebServlet("/ProcessFormServlet")
annotation matches the form’saction
.
- Confirm the
- Java Version Compatibility:
- Ensure your JDK version is compatible with Tomcat 10 (JDK 11 or higher recommended).
- File Locations:
- Verify that
index.html
andresult.jsp
are in thewebapp
directory, andProcessFormServlet.java
is insrc/main/java/com/example
.
- Verify that
Step 9: Project Structure
Your project should have the following structure:
FormDataServletDemo
├── src
│ └── main
│ ├── java
│ │ └── com.example
│ │ └── ProcessFormServlet.java
│ └── webapp
│ ├── index.html
│ ├── result.jsp
│ └── WEB-INF
│ └── web.xml
├── pom.xml (optional, if using Maven)
└── ...
Step 10: Enhancements (Optional)
- Add CSS: Style
index.html
andresult.jsp
with CSS for better appearance. - Validate Input: Add server-side validation in the Servlet to check for valid email formats.
- Error Handling: Create an error JSP page and redirect to it if form data is invalid.
- Add More Fields: Extend the form to collect additional data like phone number or address.
Summary
In this tutorial, you:
- Set up a Java web development environment with Eclipse and Tomcat.
- Created an HTML form to collect user input.
- Built a Servlet to process form data.
- Designed a JSP page to display the results.
- Configured and deployed the application.
- Tested and debugged the application.