JSP Request Dispatcher

This page discusses - JSP Request Dispatcher

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

<html>
<head>
<title>Request Dispatcher</title>
</head>
<body>
<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"/>
</form>
</body>
</html>

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.

<html>
<head>
<title>Request Dispatcher</title>
</head>
<%
String st=request.getParameter("n");
if(st==""){
getServletContext().getRequestDispatcher("/form.jsp").forward(request, response);
}
else{
getServletContext().getRequestDispatcher("/welcome.jsp").forward(request, response);
}
%>
</html>

Here is the code of welcome.jsp:

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

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

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: