how to forward and include one servlet request another servlet or jsp

If you are familiar with ASP 3.0 then you must be knowing about Server.Transfer and Server.Execute methods. Server.Transfer forwards the control to another ASP page while Server.Execute executes the given page and after that gives the control back to the caller page. Servlet API also provides us this functionality with the RequestDispatcher interface. This interface has just two methods, forward() and include which do pretty much what their names suggest.

In this article we will learn how to pass control from one Servlet to another using RequestDispatcher.forward() method and how to include response from another Servlet within the caller Servlet using RequestDispatcher.include() method.

RequestDispatcher Interface
This interface is present in the
javax.servlet package and contains only following two methods :

  • forward(ServletRequest request, ServletResponse response) Forwards a request to another resource on the same server. That resource can be a Servlet, JSP page or a simple HTML page.
  • include(ServletRequest request, ServletResponse response) Works like a server-side include ( SSI ) and includes the response from the given resource ( Servlet, JSP page, HTML page ) within the caller response.

How to get a reference to RequestDispatcher Interface ?
In order to use
forward() or include() methods we discussed above we will have to get a reference to RequestDispatcher interface. There are two ways you can do this :

  • ServletContext.getRequestDispatcher(String resource)
  • ServletRequest.getRequestDispatcher(String resource)

If your Servlet is extending HttpServletRequest then you can simply call getRequestDispatcher(String resource) to get reference to the RequestDispatcher object for the given resource. This is what we will do in the demo application later.

// req is HttpServletRequest object

 

RequestDispatcher rd;

        rd = req.getRequestDispatcher("pathToServlet");

        rd.forward(req, res);

Or you can use ServletContext's getRequestDispatcher(String resource) to do the same.

RequestDispatcher rd;

        rd = getServletContext().getRequestDispatcher("pathToServlet");

        rd.forward(req, res);

Having learned the theory about including and forwarding response using RequestDispatcher interface, it is time now that we build some demo application and demonstrate the use of these methods. We will also be learning one more thing which is setting and getting attributes from HttpServletRequest object.

RequestDispatcher Demo Application
Our demo application will consist of two Servlets. First Servlet will call
forward() and include() methods to display response from second Servlet. To demonstrate the use of HttpServletRequest attributes, we will set an attribute in the first Servlet and display that attribute from within the second Servlet.

TestDispatcherServlet1
Create a new TestDispatcherServlet1.java file in CATALINA_HOME/webapps/star/WEB-INF/classes/com/stardeveloper/servlets/ folder. You can substitute CATALINA_HOME/webapps/star/ with the path of /WEB-INF/ folder of any other application server if you want. Copy and paste the following code in it :

package com.stardeveloper.servlets;

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class TestDispatcherServlet1 extends HttpServlet {

 

        private static final String forwardTo

               = "/servlet/com.stardeveloper.servlets." +

               "TestDispatcherServlet2";

        private static final String includeIn

               = "/servlet/com.stardeveloper.servlets." +

               "TestDispatcherServlet2";     

 

        public void doGet(HttpServletRequest req, HttpServletResponse res)

               throws ServletException, IOException {

 

               res.setContentType("text/html");

               PrintWriter out = res.getWriter();

 

               out.print("<html><head><style>");

               out.print("p,form{font-family:tahoma;font-size:10pt;}");

               out.print("input{width:20;height:20;}");

               out.print("</style></head><body>");

 

               // Displaying Form

 

               out.print("<form action=\"");

               out.print( req.getRequestURI() );

               out.print("\" method=\"post\">");

               out.print("<input type=\"hidden\" name=\"mode\" ");

               out.print("value=\"forward\">");

               out.print("<input type=\"submit\" value=\" \"");

               out.print("> ");

               out.print(" Forward to another Servlet ..");

               out.print("</form>");

 

               out.print("<form action=\"");

               out.print( req.getRequestURI() );

               out.print("\" method=\"post\">");

               out.print("<input type=\"hidden\" name=\"mode\" ");

               out.print("value=\"include\">");

               out.print("<input type=\"submit\" ");

               out.print("value=\" \"> ");

               out.print(" Include another Servlet ..");

               out.print("</form>");

 

               out.print("</body></html>");

               out.close();

        }

 

        public void doPost(HttpServletRequest req, HttpServletResponse res)

               throws ServletException, IOException {

 

               String mode = req.getParameter("mode");

 

               // Forwarding to Servlet2

 

               if(mode != null && mode.equals("forward")) {

                       req.setAttribute("mode", "Forwarding Response..");

                 req.getRequestDispatcher(forwardTo).forward(req, res);

               }

 

               // Including response from Servlet2

 

               if(mode != null && mode.equals("include")) {

                       req.setAttribute("mode", "Including Response..");

                 req.getRequestDispatcher(includeIn).include(req, res);

               }

        }

}

Explanation
Our Servlet above extends
HttpServlet class and overrides doGet() and doPost() methods. We also declare two variables forwardTo and includeIn which point to the path of the second Servlet. For this example they both point to same Servlet.

 

Comments

Popular posts from this blog

Rails Memcache issues

Enabling password authentication for new ec2 box | ssh, ssh config, EC2 setup, new user in EC2, PasswordAuthentication

Ruby on Rails 3.x Skip callback and validation and reset Callback | Ruby on Rails, Skip callback, validation, reset Callback