04 ForwardDemo
04 ForwardDemo
It is the mechanism for transferring control from one web component to another. When a JSP page uses
the forward action (through an appropriate tag), the functionality provided by the Java Servlet API is
internally used. The tag be used for forwarding is jsp:forward and such behavior provided by the engine
is called as forward action.
NOTE: Forward action is an internal issue within the server and is not visible to the client. The client
assumes that the response is from originally requested page and hence the browser address bar would still
show the requested page URL.
The forward action happens within the same request context i.e. request object is available in both the
involved pages is one and the same.
When two pages are processed in the same request context then information can be shared among the
pages through the common request object. The information which we can place is known as attributes.
1
Deccansoft Software Services Adv. Java / Forward Demo
-------------------------------------------------------colorgui.jsp---------------------------------------------------------
<%
Object obj = request.getAttribute("errMsg");
if(obj == null)
obj = new String("Choose a color:");
%>
<html>
<body>
<h1>
<form action="color.jsp" method="post">
<%= obj.toString()%>
<br><br>
<input type="radio" name="color" value="red">Red
<input type="radio" name="color" value="green">Green
<input type="radio" name="color" value="blue">Blue
<br><br>
<input type="submit" name="submit" value="Proceed">
</form>
</h1
</body>
</html>
-------------------------------------------------------color.jsp-------------------------------------------------------------
<%
String colorValue = request.getParameter("color");
if(colorValue == null)
{
request.setAttribute("errMsg","You have to choose a color:");
%>
<jsp:forward page="colorgui.jsp"/>
<%
}
%>
<html>
<body text="<%= colorValue %>">
<h1 >
This is <%= colorValue %> color
</h1>
</body>
</html>