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

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.