You are not logged in!
Stardeveloper.com
Home · Articles · Forums · Advertise · Contact
Article Categories
.NET  .NET
  ASP (14)
  ASP.NET (15)
  ADO (16)
  ADO.NET (5)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (2)

J2EE  J2EE
  JSP (14)
  Servlets (9)
  Web Services (1)
  EJB (4)
  E-Commerce (1)
  J2ME (1)
Product Spotlight
Sponsor Ad
Log In
UserName Or Email:

Password:

Auto-Login:

Miscellaneous Links
  Site Log
  Submit Article

Powered by Securewebs.com

 
Home : J2EE : Servlets : General : Forwarding and Including Response from other Servlets
 

Forwarding and Including Response from other Servlets
by Faisal Khan.

Overview
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.


 ( 1 Remaining ) Next

Comments/Questions ( Threads: 1, Comments: 1 )
  1. How to forward request to servlet running on a different server from first servlet ( 0 Replies ).

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you aren't a member yet then signup, else login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

 
© 1999 - 2003 Stardeveloper.com, All Rights Reserverd. Hosted by SecureWebs.