本章目标
掌握包含语句的主要作用
掌握两种包含语句的使用及区别
包含操作
使用包含操作,可以将一些重复的代码包含进来继续使用
静态包含
静态包含语法
<%@ include file="要包含的文件路径"%>
定义要包含的页面
info.html
<h2>
<font color="#c00">info.html</font>
</h2>
info.inc
<h2>
<font color="blue">info.inc</font>
</h2>
info.jsp
<h2>
<font color="green"><%="info.jsp" %></font>
</h2>
使用静态包含指令
<%@ page language="java" contentType="text/html" pageEncoding="utf-8" %>
<html>
<head>
<title>使用静态包含以上3个文件</title>
</head>
<body>
<h2>静态包含操作</h2>
<%@include file="info.html" %>
<%@include file="info.jsp" %>
<%@include file="info.inc" %>
</body>
</html>
效果图:
静态包含的处理流程
动态包含
使用<jsp:include>指令可以完成动态包含的操作,与之前的静态包含不同,动态包含语句,可以自动区分被包含的页面是静态还是动态。
动态包含语法:
不传递参数:
<jsp:include page="{要包含的文件路径 | <%=表达式%>}" flush="true | false"/>
传递参数:
<jsp:includepage="{要包含的文件路径| <%=表达式%>}" flush="true | false">
<jsp:paramname="参数名称" value="参数内容"/>
... 可以向被包含页面中传递多个参数
</jsp:include>
使用标签指令包含
<%@ page language="java" contentType="text/html" pageEncoding="utf-8" %>
<html>
<head>
<title>使用动态包含以上3个文件</title>
</head>
<body>
<h2>动态包含操作</h2>
<jsp:include page="info.html"></jsp:include><!-- 此处为标准指令,必须完结 -->
<jsp:include page="info.jsp"></jsp:include><!-- 此处为标准指令,必须完结 -->
<jsp:include page="info.inc"></jsp:include><!-- 此处为标准指令,必须完结 -->
</body>
</html>
效果图:
定义被包含页,并接收传递的参数
<%@ page language="java" contentType="text/html" pageEncoding="utf-8" %>
<h2>参数一:<%=request.getParameter("name") %></h2>
<h2>参数二:<%=request.getParameter("info") %></h2>
定义包含页,并传递参数
<%@ page language="java" contentType="text/html" pageEncoding="utf-8" %>
<html>
<head>
<title>定义包含页,传递参数</title>
</head>
<body>
<%
String username="chaoyi";//定义一个变量
%>
<h1>动态包含并传递参数</h1>
<jsp:include page="demo3Param.jsp">
<jsp:param value="<%=username %>" name="name"/>
<jsp:param value="www.baidu.com" name="info"/>
</jsp:include><!-- 此处为标准指令,必须完结 -->
</body>
</html>
效果图:
两种包含的区别
静态包含:属于先包含后处理
动态包含:如果包含的是动态页,则先分别处理后再将处理的结果包含进来
小结
可以通过包含将一些重复的代码导入进来继续使用
在开发中建议使用动态包含完成操作