萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 結合 XML 與 XSLT 實現伺服器端 HTML 輸出

雖然現代瀏覽器大多已支援直接渲染 XML + XSLT,但考慮到舊版瀏覽器(如 IE 5.0 以下)或特殊環境下的相容性,伺服器端轉換仍是一段時間內必要的過渡方案。利用 JSP 搭配 Jakarta Taglib 標準標籤庫,即可輕鬆完成 XML 到 HTML 的轉換工作。

核心依賴套件

Apache Jakarta 專案提供的 XSL 標籤庫需依賴三個關鍵 JAR 檔:

簡化部署步驟

官方建議在 web.xml 定義標籤庫 URI 對應,但若專案固定部署於 Tomcat,可採用更簡潔的方式:

  1. 將上述三個 JAR 放入 Tomcat 的 common/lib 目錄,或加入系統 Classpath
  2. 在 JSP 頁面直接引用 JAR 路徑作為 URI:
    <%@ taglib uri="xsl.jar" prefix="xsl" %>

四種 XML + XSLT 結合模式

以官方範例 Apply.jsp 為例,展示四種實用模式:

1. 直接套用外部 XML 與 XSL 檔案

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

2. JSP 內嵌 XML 資料,套用外部 XSL

<xsl:apply xsl="/xml/employeeList.xsl">
  <?xml version="1.0" encoding="ISO-8859-1"?>
  <employees>...</employees>
</xsl:apply>

3. 使用 <xsl:include> 引入 XML,實現樣式複用

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

4. 使用 <xsl:import> 將 XML 載入頁面作用域

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

注意:路徑 /xml/ 為相對於 Tomcat 容器根目錄的絕對路徑。

範例檔案結構

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 Number</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>

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 檔案頂部加入 <?xml-stylesheet type="text/xsl" href="catalog.xsl"?>,支援 XML 的 IE 5.0+ 瀏覽器即可直接呈現相同結果,無需伺服器端處理。

copyright © 萬盛學電腦網 all rights reserved