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)進行的