include指令和<jsp:include>动做标识均可以用来包含文件,好比要在JSP页面中显示大量的纯文本,能够将定些文本文字写入静态文件中(好比记事本),而后经过include指令或者动做标识包含到该JSP页面中,这样能够让JSP页面更简洁。
html
举一个简单例子用来包含网站的banner和版权信息栏。java
我在51cto这截了三张图片。分别命名浏览器
banner.jpgjsp
center.jpgide
copyright.jpg网站
include指令的应用ui
(1)编写一个名称为top.jsp的文件,用来放置网站的banner信息spa
<%@ page pageEncoding="GB18030"%> <img src="p_w_picpaths/banner.jpg">
(2)编写一个名称为copyright.jsp的文件,用于放置网站的版权信息htm
<%@ page pageEncoding="GB18030"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <% String copyright=""; %> <!-- All Copyright©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文件,从而实现一个完整的界面:blog
<%@ 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> </td> </tr> </table> <%@ include file="copyright.jsp"%> </body> </html>
技巧:在应用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>使用<jsp:include>动做标识</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> </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指令包含文件时,因为被包含文件最终生成一个文件,因此在被包含文件、包含文件中不能有重名的变量或方法;而在应用动做标识包含文件时,因为是单独编译,因此被包含文件、包含文件中重名的变量和方法是不冲突的。