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:
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
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.
Here is the code of welcome.jsp:
The welcome.jsp display the value get from the dispatcher.jsp. using Request.get Parameter.
Output will be displayed as:
If you will entered the name then on clicking the button, welcome.jsp page shows the following message: