Use Request Dispatcher in JSP

How to Request Dispatcher in JSP? Given with example

Explanation

Request Dispatcher is used to forward a request to another page.

Example:example.jsp


<form action="process.jsp" method="post">
<input type="text" name="name">
<input type="password" name="pass">
<input type=submit>
</form>

process.jsp


<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
String message = "HI Welcome";
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
request.setAttribute("msg",message);
rd.forward(request, response);
%>

index.jsp

<%
String message = (String) request.getAttribute("msg");
out.println(" "+ message); %>

In the above example the request from the "example.jsp" is forwarded to "process.jsp". Using the "request dispatcher" function, an attribute "msg" is sent from process.jsp page to index.jsp. When the process.jsp page starts to execute, the message will be transferred from index.jsp page to process.jsp, using the "get attribute function". Finally, the message is displayed in the process.jsp page.

Ask Questions

Ask Question