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.

<!-- This is page1.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Page 1</title>
</head>
<body>
<strong>This is page 1</strong>

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

<!-- This is page2.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<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/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 pointing to page1.jsp.

How do I include other pages using jsp:include?

The <jsp:include/> tag is use to include another page fragment of a JSP page into another page. This is useful when you have a common page such as header, footer or a menu that applied to many of all of your pages.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>&lt;jsp:include/&gt; Demo</title>
</head>
<body>
<div id="header">
    <jsp:include page="common/header.jsp"/>
</div>

<div id="main">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna
    aliqua.
</div>

<div id="footer">
    <jsp:include page="common/footer.jsp"/>
</div>
</body>
</html>

Here are the page fragment of the header.jsp, footer.jsp and menu.jsp. All of them are placed in the common folder in the same location with the index.jsp file.

header.jsp

<strong><jsp:include/> Demo</strong>
<hr/>
<jsp:include page="menu.jsp"/>

footer.jsp

<hr/>
© 2009 Kode Java Org.

menu.jsp

<a href="/ex01/index.jsp">HOME</a>

When you access your page from the servlet container such as Apache Tomcat you’ll have a complete display of a page that contains header, menu, content and footer.