April 10, 2011

Forwarding request from Servlet with RequestDispatcher

The RequestDispatcher object is used to forward a request from one web component (Servlet or JSP) to another web component. The forward() method in the RequestDispatcher class does the actual forwarding.

1) Write the code for setting the request attribute and request forward in the FirstServlet.java

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.*;

public class FirstServlet extends HttpServlet {

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      System.out.println("Received request in FirstServlet");
      System.out.println("Setting  attribute in FirstServlet");
      request.setAttribute("test-attribute", "test-attribute-value");

      RequestDispatcher rd = request.getRequestDispatcher("/secondServlet");
      System.out.println("Forwarded request to SecondServlet");
      
      rd.forward(request, response);
   }
}


2) Write the code to retrieve the request attribute in the code for SecondServlet.java

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class SecondServlet extends HttpServlet implements Servlet {
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      System.out.println("Received request in SecondServlet");
      String value = (String) request.getAttribute("test-attribute");
      PrintWriter out = response.getWriter();
      out.println("Retrieving attribute in Second Servlet: " + value);
   }
}


3) Configure both the servlets in the web.xml

<servlet>
   <servlet-name>FirstServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>FirstServlet</servlet-name>
   <url-pattern>/firstServlet</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>SecondServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>SecondServlet</servlet-name>
   <url-pattern>/secondServlet</url-pattern>
</servlet-mapping>


4) Access the following URL through the browser to test the code

http://localhost:8080/WebAppName/firstServlet

No comments:

Post a Comment