include指令和<jsp:include>动作标识都可以用来包含文件,比如要在JSP页面中显示大量的纯文本,可以将定些文本文字写入静态文件中(比如记事本),然后通过include指令或者动作标识包含到该JSP页面中,这样可以让JSP页面更简洁。

举一个简单例子用来包含网站的banner和版权信息栏。

我在51cto这截了三张图片。分别命名

banner.jpg

wKiom1LTlSvBM4arAAFy9QvOwl4491.jpg

center.jpg

wKioL1LTlSHDxhuYAAHLYddwwis350.jpg

copyright.jpg

wKiom1LTlS6CquH8AACNlY8r1MU795.jpg



include指令的应用

(1)编写一个名称为top.jsp的文件,用来放置网站的banner信息

<%@ page pageEncoding="GB18030"%>
<img src="p_w_picpaths/banner.jpg">

(2)编写一个名称为copyright.jsp的文件,用于放置网站的版权信息

<%@ page pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String copyright="";
%>
<!--&nbsp;All Copyright&copy;2014 校来校网有限公司-->
<table width="778"height="61"border="0"cellpadding="0"cellspacing="0"background="p_w_picpaths/copyright.jpg">
  <tr>
                                                                                                                                                                                                                                                                                          
    <td><%=copyright %></td>
  </tr>
</table>

(3)编写一个名称为index.jsp的文件,在该页面中包括top.jsp和copyright.jsp文件,从而实现一个完整的界面:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>使用文件包含include指令</title>
</head>
<body style="margin:0px;">
<%@ include file="top.jsp" %>
<table width="778" height="279"border="0"cellpadding="0"cellspacing="0"background="p_w_picpaths/center.jpg">
<tr>
<td>&nbsp;</td>
</tr>
</table>
<%@ include file="copyright.jsp"%>
</body>
</html>

运行一下,可以看到显示界面wKioL1LTly2gLj9QAAUhlF6YS0U160.jpg

技巧:在应用include指令进行文件包含时,为了使整个页面的层次结构不发生冲突,建议在被包含页面中将<html><body>等标记删除


<jsp:include>动作标识的应用

只需将index.jsp代码修改一下即可.将include指令的<%@include file="xx.jsp"%>修改为动作标识的<jsp:include page="xx.jsp"/>

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>使用&lt;jsp:include&gt;动作标识</title>
</head>
<body style="margin:0px;">
<jsp:include page="top.jsp" />
<table width="778" height="279"border="0"cellpadding="0"cellspacing="0"background="p_w_picpaths/center.jpg">
<tr>
<td>&nbsp;</td>
</tr>
</table>
<jsp:include page="copyright.jsp"/>
</body>
</html>

include指令与<jsp:include>动作标识的区别

(1)include指令通过file属性指定被包含的文件,并且file属性不支持任何表达式;<jsp:include>动作标识通过page属性指定被包含文件,支持JSP表达式

(2)使用include指令时,被包含文件内容原封不动地插入到包含页中,然后JSP编译器再将合成后的文件最终编译成一个java文件;使用<jsp:include>动作标识包含文件时,当该标识被执行时,程序会请求转发(不是请求重定向)到被包含的页面,并将执行结果输出到浏览器中,然后返回包含页继续执行后面的代码。

(3)include指令包含文件时,由于被包含文件最终生成一个文件,所以在被包含文件、包含文件中不能有重名的变量或方法;而在应用动作标识包含文件时,由于是单独编译,所以被包含文件、包含文件中重名的变量和方法是不冲突的。