Requestdispatcher in JSP
We are going to discuss about requestdispatcher in JSP. In this example we have used JSP requestdispatcher. requestdispatcher transfers the request to another JSP page.
In this example we have created three JSP page.
- loginform.jsp
- dispatcher.jsp
- welcome.jsp
loginform.jsp:-
First of all we have created loginform.jsp.In loginform we have created one text field, one password field and a submit button. We have enter the name and password and after that we click on Submit button. This action calls upon dispatcher.jsp page and transfers the request using the getRequestDispatcher("/form.jsp").forward(request, response) method. If you have entered the name, the request is transferred to welcome.jsp page, otherwise request is transferred back to the loginform.jsp page.
dispatcher.jsp:
We have created dispatcher.jsp' page. The dispatcher.jsp' retrives the value from loginform.jsp by using Request.getParameter(). The request.getParameter() takes string type value, which include name of the attribute of loginfrom.jsp. And we use getServletContext().getRequestDispatcher("/loginform.jsp").forward(request, response) to transfer the request from login form to Welcome page. However, this method sends the request back to loginform.jsp if nothing is entered. But if only name is entered the request is transferred to Welcome.jsp page and Name is displayed.
welcome.jsp:-
The value recieved from the dispatcher.jsp. using Request.get Parameter are displayed on the Welcome page.
loginform.jsp
<head> <title>Request Dispatcher</title> </head> <body> <h2 align="center">Request Dispatcher in Jsp</h2> <form method="post" action="dispatcher.jsp" > <table align="center"> <tr> <td>Name:</td> <td><input type="text" name="fname"/></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="pwd"/></td> </tr> <tr> <td><input type="submit" value="Submit"/></td> </tr> </table> </form> </body> </html>
dispatcher.jsp
<html> <head> <title>Request Dispatcher</title> </head> <% String st=request.getParameter("fname"); String st1=request.getParameter("pwd"); if(st=="") { getServletContext().getRequestDispatcher("/form.jsp").forward(request, response); } else{ getServletContext().getRequestDispatcher("/welcome.jsp").forward(request, response); } %> </html>
welcome.jsp
<html> <body> <h2 align="center">Welcome to View Page.</h2> <h3 align="center"><font color="darklight">UserName:- <%=request.getParameter("fname")%></font></h3> <h3 align="center"><font color="darklight">Password:- <%=request.getParameter("pwd")%></font></h3> </body> </html>
output