SSI(Server Side Includes,伺服器端包含)允許在 HTML 頁面中嵌入動態內容,常用於頁首/頁尾複用、導航欄共享等場景。本文以 Apache Tomcat 6.0.29 為例,說明如何啟用並配置 SSI 支援,其他 6.x/7.x/8.x/9.x 版本配置原理相同。
web.xml 啟用 SSI Servlet$CATALINA_HOME/conf/web.xml。<servlet>
<servlet-name>ssi</servlet-name>
<servlet-class>org.apache.catalina.ssi.SSIServlet</servlet-class>
<init-param>
<param-name>buffered</param-name>
<param-value>1</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>expires</param-name>
<param-value>666</param-value> <!-- 緩存過期秒數 -->
</init-param>
<init-param>
<param-name>isVirtualWebappRelative</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>inputEncoding</param-name>
<param-value>GBK</param-value> <!-- 可選,依項目編碼調整 -->
</init-param>
<init-param>
<param-name>outputEncoding</param-name>
<param-value>GBK</param-value> <!-- 可選 -->
</init-param>
<load-on-startup>4</load-on-startup>
</servlet>
說明:inputEncoding/outputEncoding 為可選參數,若專案統一使用 UTF-8,請改為 UTF-8 或直接移除這兩個參數,由容器預設處理。
<servlet-mapping>
<servlet-name>ssi</servlet-name>
<url-pattern>*.shtml</url-pattern>
</servlet-mapping>
此處將 SSI 處理映射到 .shtml 後綴,可按需改為 *.html 或其他。
context.xml 賦予特權$CATALINA_HOME/conf/context.xml。<Context> 根節點添加 privileged="true" 屬性:<Context privileged="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- 其他預設配置保持不變 -->
</Context>
作用:SSI Servlet 需要容器特權才能存取文件系統進行包含操作,此屬性授予該權限。
test.shtml:<!--#include virtual="/header.html" -->
<h1>SSI 測試頁面</h1>
<!--#include virtual="/footer.html" -->
header.html、footer.html。https://localhost:8080/your-app/test.shtml,確認包含內容正確渲染。inputEncoding/outputEncoding 與源文件編碼一致,或統一改為 UTF-8。virtual 相對 Web 應用根目錄,file 相對當前文件目錄,請根據實際結構選擇。SecurityException,請檢查 context.xml 的 privileged="true" 是否生效,或檢查 SecurityManager 政策。