萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

JSP 整合 XML + XSLT 於伺服器端轉換輸出 HTML:Jakarta Taglib 實作指南

背景動機

XML+XSLT 可直接在 IE5+ 瀏覽器客戶端轉換,但為相容不支援 XML 的舊版瀏覽器,需在伺服器端完成轉換輸出 HTML。

依賴庫 (放入 Tomcat common/lib 或 Classpath)

JSP 宣告 Taglib (簡化版,無需 web.xml)

<%@ taglib uri="xsl.jar" prefix="xsl" %>

直接指向 jar 檔,Tomcat 會自動載入 META-INF/taglib.tld。

四種 XML+XSLT 組合方式 (Apply.jsp 範例)

1. 外部 XML + 外部 XSL

<xsl:apply xml="/xml/employees.xml" xsl="/xml/employeeList.xsl" />

2. 內嵌 XML + 外部 XSL

<xsl:apply xsl="/xml/employeeList.xsl">
  <?xml version="1.0"?>
  <employees>...</employees>
</xsl:apply>

3. include 方式:XSL 引用外部 XML

<xsl:apply xsl="/xml/employeeList.xsl">
  <xsl:include page="/xml/employees.xml" />
</xsl:apply>

4. import 方式:頁面範圍變數持有 XML

<xsl:import id="data" page="/xml/employees.xml" />
<xsl:apply nameXml="data" xsl="/xml/employeeList.xsl" />

XSLT 樣式表 (employeeList.xsl)

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
  <xsl:template match="employees">
    <table border="1" width="100%">
      <tr><th>ID</th><th>Employee Name</th><th>Phone</th></tr>
      <xsl:for-each select="employee">
        <tr>
          <td><xsl:value-of select="@id"/></td>
          <td><xsl:value-of select="last-name"/>, <xsl:value-of select="first-name"/></td>
          <td><xsl:value-of select="telephone"/></td>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>
</xsl:stylesheet>

XML 資料 (employees.xml)

<?xml version="1.0" encoding="ISO-8859-1"?>
<employees>
  <employee id="123"><first-name>John</first-name><last-name>Doe</last-name><telephone>800-555-1212</telephone></employee>
  <employee id="456"><first-name>Jane</first-name><last-name>Smith</last-name><telephone>888-555-1212</telephone></employee>
  <employee id="789"><first-name>George</first-name><last-name>Taylor</last-name><telephone>555-555-1212</telephone></employee>
</employees>

客戶端 XML+XSLT 替代方案

在 employees.xml 頂部加入:

<?xml-stylesheet type="text/xsl" href="employeeList.xsl"?>

IE5+ 直接開啟 XML 即可看到相同 HTML 輸出,零伺服器負擔。

路徑注意

/xml/ 為相對 Tomcat Context Root 的絕對路徑,非檔案系統路徑。

copyright © 萬盛學電腦網 all rights reserved