5.1 includes
There are a few more magic directives that I would like to talk about. The first such directive is the include directive . It allows you to insert another file in the place of the page where it is indicated. The general format of such a directive is:
<%@ include file="url"%>
You can specify not just a file, but, for example, another jsp-servlet, or even a url.
Example:
<%@ include file="header.jsp"%>
<%
double num = Math.random();
if (num > 0.95) {
out.print(num);
}
%>
<%@ include file="footer.jsp"%>
You can, for example, put the top part of all pages of the site in header.jsp, and the bottom part in footer.jsp and collect all pages as a constructor.
5.2 forward
Remember that classic servlets have the ability to redirect or forward to another url? In JSP, this is also possible and there is a special action for this. Its appearance is slightly different from what you saw before:
<jsp:forward page="url"/>
There is also a more advanced option - with parameters:
<jsp:forward page="url" >
<jsp:param name="Name" value="meaning"/>
<jsp:param name="Name" value="meaning"/>
<jsp:param name="Name" value="meaning"/>
</jsp:forward>
Example:
<html>
<head>
<title>The Forward Example</title>
</head>
<body>
<center>
<h2> Forward example </h2>
<jsp:forward page="login.jsp"/>
</center>
</body>
</html>
5.3 Redirect
There is no special directive for a redirect, but it can be done by calling Java code.
Example:
<body>
<%
String redirectURL = "https://codegym.cc/";
response.sendRedirect(redirectURL);
%>
</body>
This example will send 302
a redirect. If you need 301
a redirect, then you need to write a couple more lines of code:
<body>
<%
response.setStatus(301);
response.setHeader("Location", "https://codegym.cc/");
response.setHeader("Connection", "close");
%>
</body>