Practical example of RequestDispatcher.

In this post, you will learn:

  • How to create RequestDispatcher object for a web component?
  • How to set and read attributes from request scope?
  • How to use include() and forward() methods of RequestDispatcher?

As before starting a journey, we prepare an itinerary which states where we will go and how we will reach there. Similarly we should have a clear roadmap stating our objective and plan of action i.e. what we are going to do and how we will do it. The following diagram represents the roadmap of our programming journey for this post.

page flow of RequestDispatcher app

Description of the diagram:

1.0 – Client submits a request for dividerServlet.

1.1 – If request data is valid, The Servlet processes the request and displays the result along with the contents of index.html page i.e. contents of the index.html are included by the dividerServlet in its response.

1.1* – If request data isn’t valid i.e either input is non numeric or the second number is zero, then an exception occurs in the processing and request is forwarded to the handlerServlet. The exception is made available by dividerServlet to the handlerServlet as attribute of request scope.

1.2 – The handlerServlet generates error message according to the exception and displays it along with the contents of index.html page.

This is our index.html page:

<html>
<head>
<title>RequestDispatcher example application</title>
</head>
<body>
<form method="post" action="dividerServlet">
First No. <input type="text" name="num1"><br/>
Second No. <input type="text" name="num2"><br/>
<input type="submit" value="divide">
</form>
</body>
</html>

Here goes our DividerServlet:

package com.techmentro.learningpad;

import javax.servlet.http.*;
import javax.servlet.*;

import java.io.*;

public class DividerServlet extends HttpServlet {

	public void doPost(HttpServletRequest request,HttpServletResponse response) 
	{
		try
		{
		//Request data is read
		int a=Integer.parseInt(request.getParameter("num1"));
		int b=Integer.parseInt(request.getParameter("num2"));
		//Processing is done
		int c=a/b;
		//Content type of the response is set
		response.setContentType("text/html");
		//Output stream is obtained 
		PrintWriter out=response.getWriter();
		//Result is written to the output stream
		out.println("<b>Result is: "+c+"</b>");
		//divider is generated
		out.println("<hr/>");
		//RequestDispatcher is created for index.html
		RequestDispatcher rd=request.getRequestDispatcher("index.html");
		//Contents of index.html are included to the response
		rd.include(request, response);
		//Output stream is closed.
		out.close();
		}catch(Exception e)
		{
			//Caught exception is saved as attribute in request scope so that it can be shared by the handlerServlet.
			request.setAttribute("exception", e);
			//RequestDispatcher is created for handlerServlet
			RequestDispatcher rd=request.getRequestDispatcher("/handlerServlet");
			
			try {
                               //Request is forwarded to the handlerServlet
				rd.forward(request, response);
			} catch (ServletException | IOException ex) {
					ex.printStackTrace();
			}
		}
		
	}
}


The HandlerServlet:

package com.techmentro.learningpad;

import javax.servlet.http.*;
import javax.servlet.*;

import java.io.*;

public class HandlerServlet extends HttpServlet {

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
	{
		
		//Exception object is obtained from the request scope
		Exception e=(Exception)request.getAttribute("exception");
		//Exception type is checked and message is generated accordingly
		String message;
		if(e instanceof ArithmeticException)
			message="Second number must be non zero.";
		else if(e instanceof NumberFormatException)
			message="Input must be numeric.";
		else
			message=e.getMessage(); // default message for other exceptions
		
		//Content type of the response is set
		response.setContentType("text/html");
		//Output stream is obtained 
		PrintWriter out=response.getWriter();
		//Result is written to the output stream
		out.println("<b>"+message+"</b>");
		//divider is generated
		out.println("<hr/>");
		//RequestDispatcher is created for index.html
		RequestDispatcher rd=request.getRequestDispatcher("index.html");
		//Contents of index.html are included to the response
		rd.include(request, response);
		//Output stream is closed.
		out.close();
		
		
	}
}

The web.xml:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
    <servlet-name>s1</servlet-name>
    <servlet-class>com.techmentro.learningpad.DividerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>s1</servlet-name>
    <url-pattern>/dividerServlet</url-pattern>
  </servlet-mapping>
   <servlet>
    <servlet-name>s2</servlet-name>
    <servlet-class>com.techmentro.learningpad.HandlerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>s2</servlet-name>
    <url-pattern>/handlerServlet</url-pattern>
  </servlet-mapping>
</web-app>

That’s all folks, hope the example will help you. Download the source code to test it.


Its time to recap the main concepts:

  1. getRequestDispatcher() method of ServletRequest interface is used to create RequestDispatcher object.
  2. include() method of RequestDispatcher is used to include the contents of a component to the response of a servlet.
  3. forward() method of RequestDispatcher is used to forward request to another component.
  4. setAttribute() method is used to save attribute in a scope.
  5. getAttribute() method is used to fetch an attribute from a scope.

Example Source Code

If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

4 thoughts on “Practical example of RequestDispatcher.

  1. Nice tutorial !

    I was your student in 2011 , i am happy that u are providing tutorial online .
    looking forward for more tutorial .

    amit

  2. Great job!
    You are doing a great job by spreading your genuine and quality content to the masses.This is the best content I ever found online on Java technology.I hope that this should be beneficial for everyone and I don’t have words to praise for your great work and great content.

Leave a Reply

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