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" />
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" />
Following are some examples of how to use the <jsp:forward> action itself:
<jsp:forward page="login.jsp" /> <jsp:forward page="some/path/login.jsp" />
<jsp:forward page="/login.jsp" /> <jsp:forward page="/some/path/login.jsp" />
<jsp:forward page="login.jsp" /> <jsp:param name="username" value="Tom"/> </jsp:forward>
In the forwarded page, access the parameters as follows:
Username: ${param.username}
<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:
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:
Note that the URL does not change.