Servlets - SPLessons

Servlet Request Dispatcher

Chapter 12

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Servlet Request Dispatcher

Servlet Request Dispatcher

shape Description

Servlet Request Dispatcher is an interface and utilized on the server and its functionality is to dispatch the request to other resources such as HTML, JSP and the Another advantage of this interface is that includes the data of another resource. This interface is placed in javax.servlet and have the following two methods one is forward and another one is include.


Difference between forward() and include()

The both the methods are the parts of RequestDispatcher interface. These both methods will accept an objects of servlet request and reponse interfaces. The main difference is that when programmer use forward the control is transferred to the next servlet/jsp programmers are calling, while include retains the control with the current servlet, it just includes the processing done by the calling servlet/jsp .

Click Here To Know More About ServletRequest Interface

Click Here To Know More About ServletResponse Interface

forward() method

shape Conceptual
figure


Servlet Request Dispatcher, In the above diagram the response is generated by servlet2 is visible to the user, but the response generated by the servlet1 is not visible to the user.

shape Example

welcome.html

<html>
  <body>

<form action="./Splessons">
         Username:<input type="text" name="username"/>
         Email id:<input type="text" name="email"/>
                  <input type="submit" value="submit"/>
     </form>


</body>
</html>

Where just created two text boxes, one is for Username and another is for Email id and also created submit button.

web.xml

<web-app>
  
  <servlet>
     <servlet-name>ForwardServlet</servlet-name>
     <servlet-class>ForwardServlet</servlet-class>
  </servlet>
  
  <servlet>
     <servlet-name>DemoRequestDispatcher</servlet-name>
     <servlet-class>DemoRequestDispatcher</servlet-class>
  </servlet>

  <servlet-mapping>
     <servlet-name>ForwardServlet</servlet-name>
     <url-pattern>/goForwardServlet</url-pattern>
  </servlet-mapping>
  
  <servlet-mapping>
    <servlet-name>DemoRequestDispatcher</servlet-name>
    <url-pattern>/Splessons</url-pattern>
  </servlet-mapping>
  
</web-app>

Make sure that URL pattern should be match with HTML form action URL and should be also same.

DemoRequestDispatcher.java

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 DemoRequestDispatcher extends HttpServlet {

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

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
	          
	    RequestDispatcher requestDispatcher=request.getRequestDispatcher("goForwardServlet");  
	    requestDispatcher.forward(request, response);  
	   
	    }  
	  
	}

Where DemoRequestDispatcher is the class and that is extending the HtpServlet, The doGet() Method. A GET solicitation results from an ordinary solicitation for a URL or from a HTML web form that has no METHOD determined and it ought to be taken care of by doGet() technique. setContentType(“text/html”) mean that response comes in text format or html format.
ForwardServlet.java

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 ForwardServlet extends HttpServlet {

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

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String email = request.getParameter("email");
		
		out.println("
<h1>Thank you ::"+username+" From Splessons</h1>

");
		out.println("
<h2>This is your Email ID::"+email+"</h2>

");
		out.flush();
		out.close();
	}}

Here the developer will pass the values dynamically by entering username and email, flush will pump the accessible yield in the responsebuffer immediately to the program.
Output

Compile the code from HTML page and fill some data in the text box.

When click on submit button following result will be displayed.

inculde() method

shape Conceptual
figure


Servlet Request Dispatcher, In the include method concept, Response of second servlet is included in the response of the first servlet that is being sent to the client.

shape Example

 welcome.html

<html>
    <body>


<form action="./Splessons">
           Username:<input type="text" name="username"/></br>
           Email id:<input type="text" name="email"/>
                   <input type="submit" value="submit"/>
           </form>


    </body>
</html>
  

In the above HTML page just created Username and Email id and also created submit button.
 web.xml

<web-app>
		   <servlet>
		       <servlet-name>DemoInclude</servlet-name>
		       <servlet-class>requestdispatcherinclude.DemoInclude</servlet-class>
		   </servlet>
	 
		   <servlet-mapping>
		      <servlet-name>DemoInclude</servlet-name>
		      <url-pattern>/Splessons</url-pattern>
		   </servlet-mapping>
		   <welcome-file-list>
		      <welcome-file>welcome.html</welcome-file>
		      </welcome-file-list>
</web-app>

welcome file means program will be compiled from here, make sure that should be same and URL also should be match with form action in HTML.
Incude.java

package requestdispatcherinclude;

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 DemoInclude extends HttpServlet {
 
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        String email = request.getParameter("email");
         
        out.println("

<h1>Thank you ::"+username+" From Splessons

<h1>");
        out.println("h2>This is your Email ID::"+email+"</h2>


");
        out.println("

<h2>please give other username and email id</h2>


");
        RequestDispatcher requestDispatcher=request.getRequestDispatcher("/index.jsp");  
        requestDispatcher.include(request, response);  
        out.flush();
        out.close();
    }}


Here the developer used requestDispatcher.include(request, response); to give the response to the client. While using get(), developer get a reference to whatever that object as of now has as a field. So response.getWriter() will give you whichever Writer response is as of now utilizing.
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
dear users , i hope you are enjoying with SPlessons tutorials.
</body>
</html>

Output:

Compile the code from HTML page and enter fill the text box data .

When click on submit button following result will be displayed.

Summary

shape Key Points

  • Servlet Request Dispatcher – Include  is utilized to include data of different resources.
  • RequestDispatcher is the main assert of Java.
  • Developer can utilize requestdispatcher method on different pages such as JSP , HTML .