The <jsp:forward> action is used to forward the current request to another resource such as an HTML page, a JSP page or a servlet. Here’s a quick example:

<jsp:forward page="Another.jsp" />

 

1. Syntax of JSP forward action

The JSP forward action has two syntaxes. Here’s the simple one:

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

And here’s the syntax with sub elements <jsp:param> to pass additional parameters to the forwarded page:

<jsp:forward page="relative URL">

      { <jsp:param .... /> }*

</jsp:forward>

In the latter syntax, there can be one or more <jsp:param> elements in the form of:

<jsp:param name="name" value="value" />

2. Rules & Semantics of JSP forward action

3. JSP forward action Examples

Following are some examples of how to use the <jsp:forward> action itself:

<jsp:forward page="${pageName}" />

Let’s see a complete example which applies the <jsp:forward> action in real context. The divide.jsp page displays division of two numbers X and Y which are passed from URL’s query string as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Divide X by Y</title>
</head>
<body>
	<c:if test="${param.Y == 0}">
		<jsp:forward page="error.jsp" />
	</c:if>
	
	<h2 align="center">
		Result of ${param.X} / ${param.Y} is ${param.X / param.Y}
	</h2> 
</body>
</html>

In case the number Y is zero, forward to the error.jsp as follows:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
</head>
<body>
	<h2 align="center">Error, cannot divide by zero!</h2>
</body>
</html>

Type the following URL to test the divide.jsp page:

http://localhost:8080/JSPActions/divide.jsp?X=1000&Y=50

Output:

Test JSP forward 1

If we pass Y = 0, as in the following URL:

http://localhost:8080/JSPActions/divide.jsp?X=1000&Y=0

Then the error.jsp will be forwarded:

Test JSP forward 2

Note that the URL does not change.

 

Other JSP actions:

 

Other JSP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.