动态包含(<jsp:include>)
使用<jsp:include>指令可以完成动态包含的操作,与使用JSP指令中的include实现的静态包含不同,动态包含语句可以自动区分被包含的页面是静态还是动态。
如果被包含的页面是静态页面,则与静态包含相同,把文件插入后与原来的JSP文件合并成一个新的JSP页面;如果被包含的页面是动态页面,则可以进行动态的处理,然后在将处理后的结果包含进来。
动态包含语法:
n 不传递参数:
<jsp:include page="{要包含的文件路径|<%表达式%>}" flush="true|false" />
n 传递参数
<jsp:include page="{要包含的文件路径|<%=表达式%>}" flush="true|false">
<jsp:param value="参数内容" name="参数名称"/>
……可以向包含页面传递多个参数
</jsp:include>
注释:以上语法中,flush属性由于设置是否在缓冲区满了就将内容输出。可选值有true和false,默认值为true。
例1:不传递参数包含3个页面
定义包含页:
<%@ page language="java" contentType="text/html"pageEncoding="GBK"%>
<html>
<head>
<title>jsp:include</title>
</head>
<body>
<h1>动态包含操作</h1>
<jsp:include page="test.html"/>
<jsp:include page="test.jsp"/>
<jsp:include page="test.inc"/>
</body>
</html>
定义test.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test.html</title>
</head>
<body>
thisis test.html file!
</body>
</html>
定义test.jsp页面
<%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
<!DOCTYPE htmlPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>test.jsp</title>
</head>
<body>
thisis test.jsp file!
</body>
</html>
定义test.inc页面
This is test.inc file!
结果为:
例2:传递参数包含
定义被包含页info.jsp:
<%@ page language="java" contentType="text/html"pageEncoding="GBK"%>
<html>
<head>
<title>info</title>
</head>
<body>
参数1name:<%=request.getParameter("name") %><br>
参数2password::<%=request.getParameter("password") %>
</body>
</html>
定义包含页test.jsp,并传递参数name和password:
<%@ page language="java" contentType="text/html"pageEncoding="GBK"%>
<html>
<head>
<title>test</title>
</head>
<body>
<% String password="123456" ;%>
<jsp:include page="info.jsp">
<jsp:param value="test"name="name"/>
<jsp:param value="<%=password%>"name="password"/>
</jsp:include>
</body>
</html>
运行结果为:
在实际的开发中,相对于使用JSP指令中的include实现的静态包含,经常使用的是动态包含,因为动态包含可以减少错误(变量重复错误)的产生,可以传递参数。