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

  1. 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’s PATH variable.
  2. Install Eclipse IDE:
    • Download Eclipse IDE for Enterprise Java Developers from eclipse.org.
    • Install and launch Eclipse.
  3. 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, select Apache Tomcat v10.0, and point to the extracted Tomcat directory.
  4. 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.

Step 2: Create the HTML Form

We’ll create an HTML page (index.html) with a form to collect user input (name and email).

  1. Create the HTML File:
    • In the Project Explorer, navigate to FormDataServletDemo > src > main > webapp.
    • Right-click on webapp, select New > HTML File.
    • Name it index.html and click OK.
  2. Write the HTML Code:
    • Replace the content of index.html with the following:
<!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 and userEmail 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.

  1. Create the Servlet:
    • In FormDataServletDemo > src > main > java, right-click and select New > Package.
    • Name the package com.example.
    • Right-click on the com.example package, select New > Servlet.
    • Name the Servlet ProcessFormServlet.
    • Click Finish.
  2. Modify the Servlet Code:
    • Eclipse generates a template for ProcessFormServlet.java. Replace its content with:
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’s action.
  • 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 to result.jsp.

Step 4: Create the Result JSP Page

We’ll create a JSP page (result.jsp) to display the form data.

  1. Create the JSP File:
    • In FormDataServletDemo > src > main > webapp, right-click and select New > JSP File.
    • Name it result.jsp and click OK.
  2. Write the JSP Code:
    • Replace the content of result.jsp with:
<%@ 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.

  1. 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):
<?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

  1. Add the Project to Tomcat:
    • In Eclipse, go to the Servers view (if not visible, enable it via Window > Show View > Servers).
    • Right-click on Tomcat v10.0 Server, select Add and Remove.
    • Add FormDataServletDemo to the Configured list and click Finish.
  2. Start the Server:
    • Right-click on the Tomcat server in the Servers view and select Start.
  3. 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.

Step 7: Test the Application

  1. 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.
  2. Test Empty Fields:
    • Try submitting the form without entering data. The required attribute in the HTML should prevent submission.
  3. Test Navigation:
    • Click the “Back to Form” link on result.jsp to ensure it returns to index.html.

Step 8: Debugging Tips

If the application doesn’t work:

  • Check Tomcat Logs:
    • View logs in Eclipse’s Console view or in C:\apache-tomcat-10\logs.
  • Verify URL:
    • Ensure you’re accessing http://localhost:8080/FormDataServletDemo/index.html.
  • Check Servlet Mapping:
    • Confirm the @WebServlet("/ProcessFormServlet") annotation matches the form’s action.
  • Java Version Compatibility:
    • Ensure your JDK version is compatible with Tomcat 10 (JDK 11 or higher recommended).
  • File Locations:
    • Verify that index.html and result.jsp are in the webapp directory, and ProcessFormServlet.java is in src/main/java/com/example.

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 and result.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.

Scroll to Top