RequestDispatcher interface defines the following two method.

public void forward(ServletRequest req,ServletResponse resp) 
                               throws ServletException,IOException
public void include(ServletRequest req,ServletResponse resp) 
                               throws ServletException,IOException

Forward Mechanism

  1. If first Servlet is responsible for some primary process and second Servlet is responsible to generate required response then we should go for forward mechanism
  2. While forwarding, the response object will be cleared by the web-container.If 1st Servlet write any response,It will be lost
  3. forward

  4. After committing the response, we are not allowed to forward violation leads to IllegalStateException(Tomcat doesn’t implement this)
  5. Recursive forward() call raises StackOverFlowError
  6. recursiveforward

  7. After forwarding,The control comes back to execute remaining Statements after forward call.Here if we are trying to add any data to response simply it will be ignored by web container.

Example:

  1. Create FirstServlet
  2. Create SecondServlet
  3. Configure FirstServlet & SecondServlet in web.xml
  4. Deploy & Run the application

Create FirstServlet

package com.java2learn;

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 FirstServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

   	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out=response.getWriter();
		out.println("FirstServlet");
		//out.flush(); //3
		RequestDispatcher rd=request.getRequestDispatcher("/test2");
		rd.forward(request, response);
		out.println("First Servlet Again");//Ignored by web container
		System.out.println("In forward controller comes back!!");
	}
}

Create SecondServlet

package com.java2learn;

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 SecondServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

   
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out=response.getWriter();
		out.println("Second Servlet");
		
	}
}

Configure FirstServlet & SecondServlet in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>ServletDemo</display-name>

	<servlet>
		<description></description>
		<display-name>FirstServlet</display-name>
		<servlet-name>FirstServlet</servlet-name>
		<servlet-class>com.java2learn.FirstServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>FirstServlet</servlet-name>
		<url-pattern>/FirstServlet</url-pattern>
	</servlet-mapping>
	<servlet>
		<description></description>
		<display-name>SecondServlet</display-name>
		<servlet-name>SecondServlet</servlet-name>
		<servlet-class>com.java2learn.SecondServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>SecondServlet</servlet-name>
		<url-pattern>/test2</url-pattern>
	</servlet-mapping>
</web-app>

Deploy & Run the application

Output

Project Structure

PackageStructure

Download Project: ServletDemo

Note:
To remove compile time error add servlet-api.jar file to classpath(build path).

Attributes added by web container while forwarding the request

  1. While forwarding the request from one servlet to another servlet,Web container adds some attributes in “request scope“.
  2. These attributes will provide original request information to the second servlet.
Attribute Equivalent servlet request method
javax.servlet.forward.request_uri getRequestURI()
javax.servlet.forward.context_path getContextPath()
javax.servlet.forward.servlet_path getServletPath()
javax.servlet.forward.path_info getPathInfo()
javax.servlet.forward.query_string getQueryString()

Example:

This example is same as above example except the following modifications.

  1. Modify the FirstServlet
  2. Modify the SecondServlet

FirstServlet

package com.java2learn;

import java.io.IOException;
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 FirstServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

		RequestDispatcher rd = request.getRequestDispatcher("/test2");
		rd.forward(request, response);

	}
}

SecondServlet

package com.java2learn;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Inside SecondServlet");
		PrintWriter out = response.getWriter();
		Enumeration e = request.getAttributeNames();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			Object value = request.getAttribute(name);
			out.println(name + "----" + value + "</br>");
		}

	}
}

Output:

Outputattr

Download Project: ServletDemo

Note:
If we are getting RequestDispatcher by getNamedDispatcher() method then web container won’t add any attributes in request scope while forwarding or including.