Open In App

Servlet – forward() and sendRedirect() Method With Example

As we learned in the previous topics, Servlets are the Java programs that run on the server-side and generate dynamic responses to the client request. The execution of the Servlet involves the following steps:

Now, let’s consider we have a requirement to call a servlet from another servlet bypassing the information using request and response objects. We can achieve this in 2 ways, servlet provides



RequestDispatcher Interface

Servlets provide RequestDispatcher in javax.servlet package. It defines an object to dispatch the client request from one servlet to another servlet on the same server. Basically, this can be used to receive the client request object and send that object to any other resource such as Servlet, JSP, HTML file, etc. We can get the RequestDispatcher object using the below syntax:




RequestDispatcher r = req.getRequestDispatcher(String arg);

forward() method

This method forwards a request from a servlet to another servlet on the same server. It allows one servlet to do the initial processing of a request, obtains the RequestDispatcher object, and forwards the request to another servlet to generate the response.



Syntax of forward():




// r - requestDispatcher object
r.forward(req, resp);

When we are forwarding the client request using the forward() method, the client/browser doesn’t even know that the request is forwarding to another servlet file or JSP file or from which file response will be generating. There will be no change in the URL in the browser.

sendRedirect() method

It sends a temporary redirect response to the client using the specified redirect location URL given in the method and clears the buffer. Let’s consider a scenario, where we need to redirect the request from a servlet to other servlets which is in another server, in this case, we can use the sendRedirect() method so that the client/browser knows where the request is going and getting processed. 

Syntax to use sendRedirect():




resp.sendRedirect(java.lang.String location)

Let’s take an example to understand more about these two methods.

Example:

Consider a simple example – Take two integer values from the client and generate the sum and average of those two numbers. To demonstrate the use of forward() and sendRedirect() methods, we will be performing addition operations in one servlet and dispatches that request object to another servlet to perform the average operation.

Program 1: Using forward() method

Steps:

Step 1: Create a simple HTML page to take the values from the browser

Home.html




<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home Page</title>
</head>
<body>
  
<h3>Enter two numbers to find their Sum and Average</h3>
  
    <form action="add" method="get">
        <!-- Input the first number in x -->
        First Number: <input type="text" name="x">
        <br/>
        <!-- Input the second number in y -->
        Second Number: <input type="text" name="y">
        <br/>
  
        <input type="submit">
    </form>
  
</body>
</html>

Use input tags to take the values from the client, say x, y. We have a form tag that will map the servlet based on the action attribute – “add” and to the “doGet” method in the servlet when submits the page.

Step 2: Create the first servlet to get the request and perform an additional operation

AddNum.java




import java.io.IOException;
  
import javax.servlet.RequestDispatcher;
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("/add")
public class AddNum extends HttpServlet {
  
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  
        // Get the x, y parameters from the request 
        // object and save in num1, num2 variables.
        int num1 = Integer.parseInt(req.getParameter("x"));
        int num2 = Integer.parseInt(req.getParameter("y"));
  
        // Perform addition operation on num1, num2
        // and save the result in add variable.
        int add = num1 + num2;
          
        // Set the add value in 'sum' 
        // attribute of request object
        req.setAttribute("sum", add);
  
        // Get the Request Dispatcher object and pass 
        // the argument to which servlet we need to call - AvgNum.java
        RequestDispatcher reqd = req.getRequestDispatcher("avg");
        
        // Forward the Request Dispatcher object.
        reqd.forward(req, resp);
    }
  
}

Step 3: Create a second servlet to perform the average operation and send the response.

AvgNum.java




import java.io.IOException;
import java.io.PrintWriter;
  
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("/avg")
public class AvgNum extends HttpServlet {
  
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  
        // Get the 'sum' attribute value from the request
        int sum = (int) req.getAttribute("sum");
  
        // perform the average operation and 
        // save the result in 'avg' variable.
        float avg = (float) (sum / 2.0);
          
        // Get the PrintWriter object to write 
        // the output in the response to the browser.
        PrintWriter out = resp.getWriter();
        out.println("Sum is: " + sum);
        out.println("Average is: " + avg);
  
    }
  
}

Execution:

Home.html

Home Page




<form action="add" method="get">




@WebServlet("/add")




// Get the Request Dispatcher object and pass the argument
// to which servlet we need to call - AvgNum.java
RequestDispatcher reqd = req.getRequestDispatcher("avg");
// Forward the Request Dispatcher object.
reqd.forward(req, resp);




@WebServlet("/avg")

Result – forward()

Program 2: Using sendRedirect() method

Now, we will use the sendRedirect() method instead of forward() in the same example.

AddNum.java




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("/add")
public class AddNum extends HttpServlet {
  
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  
        // Get the x, y parameters from the request
        // object and save in num1, num2 variables.
        int num1 = Integer.parseInt(req.getParameter("x"));
        int num2 = Integer.parseInt(req.getParameter("y"));
  
        // Perform addition operation on num1, 
        // num2 and save the result in add variable.
        int add = num1 + num2;
          
        // Redirect the response to the
        // other servlet - AvgNum.java
        resp.sendRedirect("avg?sum="+add);
  
    }
  
}

AvgNum.java




import java.io.IOException;
import java.io.PrintWriter;
  
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("/avg")
public class AvgNum extends HttpServlet {
  
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  
        // Get the 'sum' parameter from the request
        int sum = Integer.parseInt(req.getParameter("sum"));
  
        // perform the average operation and
        // save the result in 'avg' variable.
        float avg = (float) (sum / 2.0);
          
        // Get the PrintWriter object to write the
        // output in the response to the browser.
        PrintWriter out = resp.getWriter();
        out.println("Sum is: " + sum);
        out.println("Average is: " + avg);
  
    }
  
}

Execution:

Home Page

Conclusion

When compared to both outputs,

using forward()

using sendRedirect()

We can see there is only one request and response object while using the forward() method. Internally, the forward() method will pass the same request from one servlet to another servlet without knowing at the browser side. But while using the sendRedirect() method, there are two requests and responses, the first servlet receives the request from the browser and redirects that request to another servlet, so another request and response will be formed in the second servlet and that response will be given to the browser.


Article Tags :