• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Request Dispatcher In Servlet

January 31, 2014 //  by Krishna Srinivasan//  Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Request Dispatcher

While developing web applications we need to distribute the request processing and response generation to multiple servlet objects. So we need to dispatch requests from one component to another component. This can be done by using RequestDispatcher interface.

RequestDispatcher interface is implemented by servlet container to dispatch or to pass the request to a web resource such as Servlet, HTML page or JSP page.

To dispatch the request from Servlet or JSP to web resource using RequestDispatcher we need to perform following steps:

  • Get a RequestDispatcher object reference
  • Using include () and forward () methods of RequestDispatcher.

Getting a RequestDispatcher object

RequestDispatcher object can be obtained by using following methods.

  • The getRequestDispacther () method of ServletContext.
  • The getNamedDispacther () method of ServletContext.
  • The getRequestDispacther () method of ServletRequest.

The getRequestDispacther () method of ServletContext

This method takes String argument to locate the resource to which request is to be dispatched. When this method is called, the container locates given path. Path should start with the / character. If given path does not start with / character it throws IllegalArgumentException.

The getNamedDispacther () method of ServletContext

This method takes String argument used to locate Servlet to which request is to be dispatched. When this method is called, the container locates the Servlet with given name in the context.

The getRequestDispacther () method of ServletRequest

This method obtains the RequestDispatcher object using path to the current request. The Servlet container builds complete path and locates the resource provided in the getRequestDispacther() method of ServletContext.

Using include () and forward () methods of RequestDispatcher

The include() method: This method includes the response of another Servlet into the calling Servlet. This method can be invoked from calling Servlet while servicing the request. It includes contents of resource such as Servlet, JSP page or HTML page in the response. If we want generate response in the source servlet then we should make use of include () method.

The forward() method: This method is used to forward requests to resource such as Servlet, JSP file or HTML page on the server. This method checks whether servlet has obtained the response and output in the response buffer. If buffer is not committed, the content is cleared. However if the buffer is already committed, it throws IllegalStateException. It implies that after invoking forward () method, the Servlet cannot add any response content.

Request Dispatcher Example

Now let us write an example to see how RequestDispatcher works. First write an HTML file called hello.html. This file will contain a form, to enter some text.

Listing 1:hello.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
   <form action="Simple" method="get">
	Name: <input type="text" name="uname"><br />
       <input type="submit" value="Submit" />
   </form>
</body>
</html>

Now on submit of the the data, an action Simple.java which is a servlet would be called. In this servlet we are checking if the entered String equals “Javabeat”. If true, then the request is dispatched to another servlet Welcome. Else and error message is displayed and the request dispatcher calls the hello.html again.

Listing 2: Simple.java servlet

package javabeat.net.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Simple extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		String str = request.getParameter("uname");
		if (str.equals("Javabeat")) {
			RequestDispatcher rd = request.getRequestDispatcher("Welcome");
			rd.forward(request, response);

		} else {
			out.print("Sorry username error--redirecting to login page!");
			RequestDispatcher rd = request.getRequestDispatcher("hello.html");
			rd.include(request, response);
		}

	}
}

Listing 2: Welcome.java servlet

package javabeat.net.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Welcome extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		String uname = request.getParameter("uname");
		out.print("Welcome " + uname);
	}
}

Now that everything is ready, execute the hello.html. Right mouse click on hello.html select Run > Run As and output would appear as below:
servlet_reqdis_1

Now enter data as “Javabeat” and click on submit button:
servlet_reqdis_2

servlet_reqdis_3

Now enter data as “somename” and click on submit button:

servlet_reqdis_4

servlet_reqdis_5

Previous Tutorial : Servlet Context  || Next Tutorial : sendRedirect in Servlet

Category: Java EETag: Servlets Tutorials

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « How To Display Environment Variables In Java
Next Post: How To Display Your System Font Families in Java »

Reader Interactions

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact