No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

Connect Two Servlet with Request Dispatcher

  • Home
  • Java
  • Connect Two Servlet with Request Dispatcher
java full stack developement,skills101, java, web development, java development roadmap 2024,java classes, best java classes

Lets try to create one html page and retrieve data to a servlet and add those data and send this data to another servlet to print.

Let’s create a sequence of steps to achieve this:

  1. Create an HTML form to collect two numbers from the user.
  2. Create a servlet to retrieve the numbers from the form, add them, and then forward the result to another servlet.
  3. The second servlet will display the result.

Step 1: Create the HTML Form

Create an HTML file named input.html.

<!DOCTYPE html>
<html>
<head>
    <title>Number Addition</title>
</head>
<body>
    <h2>Add Two Numbers</h2>
    <form action="add" method="post">
        <label for="number1">Number 1:</label>
        <input type="text" id="number1" name="number1"><br><br>
        <label for="number2">Number 2:</label>
        <input type="text" id="number2" name="number2"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Step 2: Create the First Servlet (AddServlet)

Create a new Java class named AddServlet.java. This servlet will retrieve the numbers from the form, add them, and forward the result to the second servlet.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve data from the form
        int number1 = Integer.parseInt(request.getParameter("number1"));
        int number2 = Integer.parseInt(request.getParameter("number2"));
        
        // Calculate the sum
        int sum = number1 + number2;

        // Set the sum as a request attribute
        request.setAttribute("sum", sum);

        // Forward the request to the ResultServlet
        RequestDispatcher dispatcher = request.getRequestDispatcher("result");
        dispatcher.forward(request, response);
    }
}

Step 3: Create the Second Servlet (ResultServlet)

Create a new Java class named ResultServlet.java. This servlet will display the result sent from the AddServlet.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/result")
public class ResultServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve the sum from the request attribute
        int sum = (int) request.getAttribute("sum");

        // Display the result
        response.setContentType("text/html");
        response.getWriter().println("<h1>Result</h1>");
        response.getWriter().println("<p>The sum is: " + sum + "</p>");
    }
}

Explanation

  1. HTML Form (input.html):
    • Collects two numbers from the user and submits the form data to the /add URL using a POST request.
  2. AddServlet (AddServlet.java):
    • Mapped to /add.
    • Retrieves the two numbers from the form, calculates their sum, and sets the result as a request attribute.
    • Forwards the request to ResultServlet using RequestDispatcher.
  3. ResultServlet (ResultServlet.java):
    • Mapped to /result.
    • Retrieves the sum from the request attribute and displays it.

Step 4: Deploy Your Application

  1. Place input.html in the web directory (e.g., webapps/your_project_name if using Tomcat).
  2. Compile and deploy AddServlet.java and ResultServlet.java as part of your web application.
  3. Start your server (Tomcat) and navigate to http://localhost:8080/your_project_name/input.html in your web browser.

When you fill out the form and click “Submit,” the AddServlet will handle the request, add the numbers, and forward the result to the ResultServlet, which will then display the sum.

Leave A Comment

Your email address will not be published. Required fields are marked *