How do I forward request to another page in JSP?

To forward a request from one page to another JSP page we can use the <jsp:forward> action. This action has a page attribute where we can specify the target page of the forward action. If we want to pass parameter to another page we can include a <jsp:param> in the forward action. But make sure that the forward page is a JSP page to enable the parameters to be processed.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Forward Demo</title>
</head>
<body>

<jsp:forward page="message.jsp">
    <jsp:param name="message" value="Welcome!"/>
</jsp:forward>

</body>
</html>

And here is how to read the parameters in the message.jsp.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Message: ${param["message"]}</title>
</head>
<body>
Message: ${param["message"]}
</body>
</html>
jsp:forward Demo

jsp:forward Demo

When you access the jspForward.jsp page in the web browser what you will see is the content of the message.jsp page. This is because the <jsp:forward> action forward your request to the message.jsp before returning the response back to the browser for display.

How do I forward to other page using <jsp:forward>?

The <jsp:forward/> tag forward user request to other page. For example, a user request page1.jsp and in this page the server found a <jsp:forward page="page2.jsp"/>. The server immediately stop the processing of page1.jsp and jump to the page2.jsp.

Let see an example of using <jsp:forward/> tag.

page1.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page 1</title>
</head>
<body>
<strong>This is page 1</strong>

<jsp:forward page="page2.jsp"/>
</body>
</html>

page2.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page 2</title>
</head>
<body>
<strong>This is page 2</strong>
</body>
</html>

When you try to run the example above by accessing the URL http://localhost:8080/forward/page1.jsp you are going to see the content of page2.jsp instead of page1.jsp. It’s happen because on the server side page1.jsp forward your request to the page2.jsp. But if you look at your browser URL address it will still point to page1.jsp.

Here is the directory structure of our example:

.
├─ pom.xml
└─ src
   └─ main
      └─ webapp
         └─ forward
            └─ page1.jsp
            └─ page2.jsp

Maven Dependencies

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Maven Central