Home Jsp JSP Request Dispatcher


Share on Google+Share on Google+

JSP Request Dispatcher

This page discusses - JSP Request Dispatcher

JSP Request Dispatcher


In this section, we are using the RequestDispatcher class to transfer the current request to another jsp page. You can see in the given example, we have create three jsp page:
1) form.jsp
2) dispatcher.jsp
3) welcome.jsp

Through the form.jsp page, we prompt the user to enter the name. On submitting the button, action is called upon and dispatcher.jsp page transfers the request using the getRequestDispatcher("/form.jsp").forward(request, response) method. If you entered the name, the request is transferred to welcome.jsp page, otherwise request is transferred back to the form.jsp page.

Understand with Example

The Tutorial illustrate an example from 'JSP Request Dispatcher'. To understand and elaborate example we create a form.jsp. The form.jsp allows the user to enter the name and has a submit button. On submitting the button, the action button transfer the request page information to dispatcher.jsp.  

Here is the code of form.jsp

<title>Request Dispatcher</title>
<h2>Request Dispatcher in Jsp</h2>
<form method="post" action="dispatcher.jsp" >
Enter your Name: <input type="text" name="n"/>
<input type="submit" value="Submit"/>

Here is the code of dispatcher.jsp:

We create another page 'dispatcher.jsp' which retrieve the value from form.jsp using Request.get Parameter ( ) . This method takes a string type parameter which include the name of the attribute of form page.jsp. The if loop check for the string value, in case the string don't contain any value, the getServletContext().getRequestDispatcher("/form.jsp").forward(request, response) send the request page back to form.jsp. Otherwise it transfer the page information from dispatcher.jsp to welcome.jsp.

<title>Request Dispatcher</title>
String st=request.getParameter("n");
getServletContext().getRequestDispatcher("/form.jsp").forward(request, response);
getServletContext().getRequestDispatcher("/welcome.jsp").forward(request, response);

Here is the code of welcome.jsp:

The welcome.jsp display the value get from the dispatcher.jsp. using Request.get Parameter.

<h3><font color="red">Hello <%=request.getParameter("n")%></font></h3>
<h2>Welcome to this page.</h2>

Output will be displayed as:

If you will entered the name then on clicking the button, welcome.jsp page shows the following message:


Download Source Code:



If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Ask Questions?    Discuss: JSP Request Dispatcher  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image