You are on page 1of 2

Deccansoft Software Services Adv.

Java / Forward Demo


-------------------------------------------------------------------------------------------------------------------------------
Transferring Control to Another Web Component:

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.

<jsp:forward page="some page" />

When the forward tag is encountered, the engine behaviour is as follows:


1) Processing of the current page is stopped
2) The buffer is cleared
3) Request is transferred to the forwarded page
4) The client would see response from the forwarded page
5) Control does not go back to the forwarding page

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.

Scope related methods in request object:


request.setAttribute (String name, Object value)
Object = request.getAttribute (String name)
Enumeration = request.getAttributeNames ()
request.removeAttribute (String name)

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>

You might also like