JSP <jsp:forward> Action



JSP Action Element :

  1. JSP jsp:forward Action elements is used to terminate the action on the current page and Request is forwarded to another page or resource
  2. JSP jsp:forward will forward request to another JSP page,Servlet or any static page such as html
  3. Request can be made to the another resources by passing parameter.

Syntax :

Below syntax is used when we need to forward request along with some parameters.

<jsp:forward page="next.jsp"> 
   <jsp:param ... /> 
   <jsp:param ... /> 
   <jsp:param ... /> 
   ...
   <jsp:param ... /> 
</jsp:forward>

Below is alternate syntax used to forward the request without passing the parameters.

<jsp:forward page="Relative URL" />

If page is in the same directory where the main page resides then use page name itself can be used.

Attribute Description
page Should consist of a relative URL of another resource such as a static page, another JSP page, or a Java Servlet.

Example :

Consider the following jsp index.jsp used to show the message -

<html> 
<head>
<title>JSP forward action Tag Example</title>
</head>
<body> 
<p align="center">Welcome to JSP</p>
	<jsp:forward page="output.jsp" /> 
</body> 
</html>

Now consider our output.jsp which will display only message -

<html> 
<head>
<title>JSP forward action Tag Example</title>
</head>
<body> 
Welcome to Output JSP
</body> 
</html>

Output :

Now when we run the above index.jsp then we request will be forwared to the the output.jsp and following output will be displayed -

Welcome to Output JSP

forward jsp action
You can see the url of the page that we run and output text. It clearly indicates that when we run index.jsp then content of the output.jsp is getting displayed.

JSP Forward Action : Using Parameter Passing

Consider the below example of index.jsp -

<html> 
<head>
<title>JSP forward action Tag Example</title>
</head>
<body> 
<p align="center">Welcome to JSP</p>
<jsp:forward page="output.jsp"> 
	<jsp:param name="name" value="Pritesh" /> 
	<jsp:param name="site" value="www.c4learn.com" /> 
</jsp:forward> 
</body> 
</html>

Now consider the output.jsp -

<html> 
<head>
<title>JSP forward action Tag Example</title>
</head>
<body> 
Details of Site :<hr />
Author : <%=request.getParameter("name") %><br />
Site   : <%=request.getParameter("site") %><br />
</body> 
</html>

Output :

Using request.getParameter() method we can retrieve the parameters passed by index.jsp, Above code will results into following output -
jsp forward action without action