JSP forward and include tag

In JSP, forward and include tags are the most frequently used action tags. Unlike Servlets, there is no need to create object of RequestDispatcher interface to use the functionality of forward and include. Thus, JSP provides direct tag for the same purpose.

JSP forward Tag

In JSP, forward tag terminates the execution of current JSP page and forward the control to new page which can be JSP, Servlet, HTML or any other. The response of new page is displayed to the user.

Syntax: -

<jsp:forward page="filename">

JSP include Tag

The role of include tag is to dispatch the external resource in the JSP page. The external resource can be JSP, Servlet HTML or any other page. 

Syntax: -

<jsp:include page="filename">

Example of forward and include Tag

This example represents the functionality of both, forward and include tag.

index.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tutorial and Example</title>
</head>
<body>
<font size="5">
<form action="CheckPage.jsp">
Name:<input type="text" name="name"> <br>
Password:<input type="password" name="pass"> <br>
<input type="submit" value="submit">
</form>
</font>
</body>
</html>

CheckPage.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tutorial and Example</title>
</head>
<body>
<font size="5">
<% String s=request.getParameter("pass");
if(s.length()>4)
{
%>
<jsp:forward page="WelcomePage.jsp"></jsp:forward>
<%    
}
else
{
    %>  
    <jsp:forward page="Error.jsp"></jsp:forward>
<%
}
%>
</font>
</body>
</html>

WelcomePage.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tutorial and Example</title>
</head>
<body>
<font size="5">
<% String s=request.getParameter("name"); %>
<%="Welcome : "+s %>
</font>
</body>
</html>

Error.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tutorial and Example</title>
</head>
<body>
<font size="5">
Error: Password must be more than 4 digits <br>
<jsp:include page="index.jsp"></jsp:include>
</font>
</body>
</html>
Output

The entered password must be more than 4 digits.

Enter a strong password (i.e. more than 4 digits) to see welcome page.