JSP - 包含指令



include 指令用於在翻譯階段包含檔案。此指令告訴容器在翻譯階段將其他外部檔案的內容與當前 JSP 合併。您可以在 JSP 頁面中的任何位置編寫include 指令。

此指令的一般使用形式如下:

<%@ include file = "relative url" >

include 指令中的檔名實際上是一個相對 URL。如果您只指定檔名而不帶關聯路徑,則 JSP 編譯器會假定該檔案與您的 JSP 位於同一目錄中。

您可以將上述語法的 XML 等效形式編寫如下:

<jsp:directive.include file = "relative url" />

示例

include 指令的一個很好的示例是將公共頁首和頁尾包含在多個內容頁面中。

讓我們定義以下三個檔案(a) header.jsp、(b)footer.jsp(c)main.jsp,如下所示:

以下是 header.jsp 的內容:

<%! 
   int pageCount = 0;
   void addCount() {
      pageCount++;
   }
%>

<% addCount(); %>

<html>
   <head>
      <title>The include Directive Example</title>
   </head>
   
   <body>
      <center>
         <h2>The include Directive Example</h2>
         <p>This site has been visited <%= pageCount %> times.</p>
      </center>
      <br/><br/>

以下是 footer.jsp 的內容:

      <br/><br/>
      <center>
         <p>Copyright © 2010</p>
      </center>
   </body>
</html>

最後,以下是 main.jsp 的內容:

<%@ include file = "header.jsp" %>
<center>
   <p>Thanks for visiting my page.</p>
</center>
<%@ include file = "footer.jsp" %>

現在讓我們將所有這些檔案儲存在根目錄中,並嘗試訪問 main.jsp。您將收到以下輸出:

The include Directive Example



This site has been visited 1 times.

Thanks for visiting my page.

Copyright © 2010

重新整理 main.jsp,您會發現頁面點選計數器不斷增加。

您可以根據自己的創意設計網頁;建議您將網站的動態部分儲存在單獨的檔案中,然後將它們包含在主檔案中。當您需要更改網頁的一部分時,這將使操作變得更容易。

jsp_directives.htm
廣告

© . All rights reserved.