静态包含
静态包含指令是在JSP编译时插入一个包含文本或代码的文件,这个包含的过程是静态的,而包含的文件可以是JSP文件、HTML文件、文本文件或是一段java程序。
静态包含的语法:
<%@include file=”要包含的文件路径”%>
定义3个被包含的文件:info.htm、info.jsp、info.txt
实例1:info.htm
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h2>
<font style="color:red;">info.html</font>
</h2>
</body>
</html>
实例2:info.jsp
<%@page language="java" contentType="text/html" pageEncoding="GBK"%>
<%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h2>
<font style="color:green;">info.jsp</font>
</h2>
<%
//定义一个变量
int num=3;
%>
</body>
</html>
实例3:info.txt
内容随便写
实例4:包含的文件(正常)
<%@page language="java" contentType="text/html" pageEncoding="GBK"%>
<%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h1>静态包含操作</h1>
<%@include file="info.html" %>
<%@include file="info.jsp" %>
<%@include file="info.txt" %>
</body>
</html>
实例5:包含的文件(异常)
<%@page language="java" contentType="text/html" pageEncoding="GBK"%>
<%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h1>静态包含操作</h1>
<%@include file="info.html" %>
<%@include file="info.jsp" %>
<%@include file="info.txt" %>
<%
int num =3;//异常
%>
</body>
</html>
在静态包含中,实际上是先将包含的3个文件的内容导入到include.jsp中,然后再一起进行编译,最后在将一份整体的内容展现出来,也就是先包含,再将全部的内容的代码的编译处理。
动态包含
实例6:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<!-- 动态包含 -->
<jsp:include page="info.html"></jsp:include>
<jsp:include page="info.jsp"></jsp:include>
<jsp:include page="info2.jsp"></jsp:include>
<jsp:include page="info.txt"></jsp:include>
<%
int num =4;//正常运行
%>
</body>
</html>
通过实例5和实例6大家可以比较下:
使用<jsp:include >指令可以完成动态包含的操作,与前面的静态包含不同,动态包含语句可以自动区分被包含的页面是静态的还是动态的,如果是静态的页面,则与静态的包含一样,将内容包含进来处理;而如果被包含的页面是动态的,则可以先动态的处理,然后再将处理后的结果包含进来。
动态包含参数传递
以下代码结合使用
实例7:包含页面
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<html>
<head>
<title>包含页面</title>
</head>
<body>
<h1>动态包含操作并接受参数</h1>
<%
String username = "zhangsans";
%>
<jsp:include page="receive.jsp">
<jsp:param value="<%=username%>" name="name" />
<jsp:param value="23" name="age" />
</jsp:include>
</body>
</html>
实例8 :被包含页面
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<html>
<head>
<title>被包含页面</title>
</head>
<body>
<h1>
参数一:<%=request.getParameter("name")%></h1>
<h1>
参数二:<%=request.getParameter("age")%></h1>
</body>
</html>
使用动态包含的第二种语法形式,可以向被包含的页面中传递参数,被包含的页面可以使用request.getParameter()方法进行参数的接收。