JSP 之 静态包含 <%@ include %>
现在我们来看看JSP 的静态包含指令: <%@ include %>
我们新建一个工程TestInclude
然后加入文件:
Index.jsp:
<%@ page language="java"import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
<body>
<%@ includefile="curDate" %>
<%@ includefile="curDate.jsp" %>
<%@ includefile="curDate.html" %>
<p>this is user's area</p>
</body>
</html>
curDate: (不带后缀)
<p>curDate: <%=new Date()%></p> <!-- curDate -->
curDate.jsp:
<p>curDate.jsp: <%=new Date()%></p> <!—curDate.jsp-->
curDate.html:
<p>curDate.html: <%=newDate()%></p> <!—curDate.html -->
查看结果: http://localhost:8080/TestInclude/index.jsp
查看其源代码:
查看Tomcat 工作目录:
查看index_jsp.java文件:
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.22
* Generated at: 2011-11-04 11:17:58 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
…………这里省略…..
try {
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("<html>\r\n");
out.write(" <body>\r\n");
out.write(" \t");
out.write("<p>curDate: ");
out.print(new Date());
out.write("</p> <!-- curDate -->");
out.write("\r\n");
out.write(" \t");
out.write("<p>curDate.jsp: ");
out.print(new Date());
out.write("</p> <!-- curDate -->");
out.write("\r\n");
out.write(" \t");
out.write("<p>curDate.html: ");
out.print(new Date());
out.write("</p> <!-- curDate.html -->");
out.write("\r\n");
out.write(" \t<p>this is user's area</p>\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
分析总结:
Tomcat工作目录下只编译了index.jsp文件, curDate.jsp没有被生成.java文件,再对比了.html和无后缀的文件,其内容是相似的,所以这个静态包含指令,其实和被包含的文件的格式无关,只有是本文即可,所以可推测到其”包含”这个动作,就是要index.jsp被转成.java(Servlet)前,要做的工作仅仅是把目标文件包含进去index.jsp中,简单替换了原有的指令而已…
so 静态包含 <%@ include %> == 文本替换
PS:
Directive(编译指令)相当于在编译期间的命令
格式:
<%@Directive 属性=“属性值”%>
这种格式的指令都是编译期进行的,而不是在运行时(Runtime)进行的