Tomcat目錄文件列表功能和定制化

沒(méi)有需求,就沒(méi)有折騰

不過(guò)我還是喜歡折騰,只要有目的,就要嗨起來(lái)。

先說(shuō)一下背景。
某天,產(chǎn)品小伙伴過(guò)來(lái)提了一個(gè)需求:能不能把公司的需求文檔以列表的方式展示出來(lái),當(dāng)開(kāi)發(fā)者需要哪個(gè)的時(shí)候,自己在目錄中尋找并點(diǎn)擊進(jìn)入(需要哪個(gè)點(diǎn)哪個(gè),so easy),也就不用記錄那么多文檔url了。
另外說(shuō)明一下,公司的需求文檔是以文件夾和html組織形式部署在tomcat的,版本8,這是前提。
聽(tīng)完需求,格子的腦袋就開(kāi)始運(yùn)轉(zhuǎn)起來(lái),這不是分分鐘能搞定的事嗎,袖子擼起來(lái),說(shuō)做咱做。

眾(Java)所(程序猿)周知,一般訪問(wèn)Tomcat某個(gè)目錄時(shí),如果沒(méi)有設(shè)置歡迎文件的話,是會(huì)報(bào)找不到的異常的(也就是傳說(shuō)中的404),如果你開(kāi)心的話,是可以設(shè)置歡迎文件來(lái)防止404,顯然這個(gè)方法是解決不了我們的需求的,確切來(lái)說(shuō),是沒(méi)辦法簡(jiǎn)單解決。(如果非要解決,思路無(wú)非是這樣,設(shè)置歡迎文件,在歡迎文件里讀取當(dāng)前目錄,并將目錄下的子目錄遍歷作為列表展示給訪問(wèn)者,這里不做討論,愛(ài)咋咋地)

傳說(shuō)中的404

片頭結(jié)束,開(kāi)始正片,tomcat是提供目錄訪問(wèn)功能的,請(qǐng)不要眨眼觀看下列實(shí)驗(yàn)步驟。

1、在webapp下新建目錄,并啟動(dòng)tomcat

#目錄結(jié)構(gòu)
/webapps
    /zoro
        /dir1
        /dir2
        /dir3
        /dir4
        /dir5
        /dir6
#啟動(dòng)tomcat

#如果是Windows請(qǐng)執(zhí)行startup.bat
→startup.bat(雙擊運(yùn)行)

#如果是linux請(qǐng)執(zhí)行startup.sh
cd $CATALINA_BASE/bin
chmod *.sh (如果已賦權(quán),請(qǐng)忽略)
./bin/startup.sh

接下來(lái),訪問(wèn)http://localhost/zoro觀看效果,是不是看到了,甩手就是一個(gè)404

Tomcat原生404

2、修改tomcat配置

#編輯tomcat配置目錄下的web的xml文件
vim $CATALINA_BASE/conf/web.xml
#大概在100來(lái)行,可以看到如下一串神秘代碼
<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>

把上面的listings的值改為true,然后重啟tomcat查看效果。

Tomcat原生列表目錄

是不是很丑,我也覺(jué)得很丑,對(duì)于我這種顏控來(lái)說(shuō),簡(jiǎn)直不忍直視,看不下去了,那就開(kāi)始整容。

3、定制目錄列表

在web.xml的90幾行(上面那串神秘代碼之上),有這樣一些注釋

<!-- ================== Built In Servlet Definitions ==================== -->


  <!-- The default servlet for all web applications, that serves static     -->
  <!-- resources.  It processes all requests that are not mapped to other   -->
  <!-- servlets with servlet mappings (defined either here or in your own   -->
  <!-- web.xml file).  This servlet supports the following initialization   -->
  <!-- parameters (default values are in square brackets):                  -->
  <!--                                                                      -->
  <!--   debug               Debugging detail level for messages logged     -->
  <!--                       by this servlet.  [0]                          -->
  <!--                                                                      -->
  <!--   fileEncoding        Encoding to be used to read static resources   -->
  <!--                       [platform default]                             -->
  <!--                                                                      -->
  <!--   input               Input buffer size (in bytes) when reading      -->
  <!--                       resources to be served.  [2048]                -->
  <!--                                                                      -->
  <!--   listings            Should directory listings be produced if there -->
  <!--                       is no welcome file in this directory?  [false] -->
  <!--                       WARNING: Listings for directories with many    -->
  <!--                       entries can be slow and may consume            -->
  <!--                       significant proportions of server resources.   -->
  <!--                                                                      -->
  <!--   output              Output buffer size (in bytes) when writing     -->
  <!--                       resources to be served.  [2048]                -->
  <!--                                                                      -->
  <!--   readonly            Is this context "read only", so HTTP           -->
  <!--                       commands like PUT and DELETE are               -->
  <!--                       rejected?  [true]                              -->
  <!--                                                                      -->
  <!--   readmeFile          File to display together with the directory    -->
  <!--                       contents. [null]                               -->
  <!--                                                                      -->
  <!--   sendfileSize        If the connector used supports sendfile, this  -->
  <!--                       represents the minimal file size in KB for     -->
  <!--                       which sendfile will be used. Use a negative    -->
  <!--                       value to always disable sendfile.  [48]        -->
  <!--                                                                      -->
  <!--   useAcceptRanges     Should the Accept-Ranges header be included    -->
  <!--                       in responses where appropriate? [true]         -->
  <!--                                                                      -->
  <!--  For directory listing customization. Checks localXsltFile, then     -->
  <!--  globalXsltFile, then defaults to original behavior.                 -->
  <!--                                                                      -->
  <!--   localXsltFile       Make directory listings an XML doc and         -->
  <!--                       pass the result to this style sheet residing   -->
  <!--                       in that directory. This overrides              -->
  <!--                       contextXsltFile and globalXsltFile[null]       -->
  <!--                                                                      -->
  <!--   contextXsltFile     Make directory listings an XML doc and         -->
  <!--                       pass the result to this style sheet which is   -->
  <!--                       relative to the context root. This overrides   -->
  <!--                       globalXsltFile[null]                           -->
  <!--                                                                      -->
  <!--   globalXsltFile      Site wide configuration version of             -->
  <!--                       localXsltFile. This argument must either be an -->
  <!--                       absolute or relative (to either                -->
  <!--                       $CATALINA_BASE/conf or $CATALINA_HOME/conf)    -->
  <!--                       path that points to a location below either    -->
  <!--                       $CATALINA_BASE/conf (checked first) or         -->
  <!--                       $CATALINA_HOME/conf (checked second).[null]    -->
  <!--                                                                      -->
  <!--   showServerInfo      Should server information be presented in the  -->
  <!--                       response sent to clients when directory        -->
  <!--                       listings is enabled? [true]                    -->
屬性 描述
debug 調(diào)試級(jí)別,如果不是 tomcat 開(kāi)發(fā)人員,則沒(méi)有什么太大的用處。截止本文寫(xiě)作時(shí),有用的值是 0、1、11、1000。默認(rèn)值為0。
listings 如果沒(méi)有歡迎文件,要不要顯示目錄列表?值可以是true 或 false。歡迎文件是servlet api的一部分。警告:目錄列表中含有的很多項(xiàng)目都是非常消耗服務(wù)性能的,如果對(duì)大型目錄列表多次進(jìn)行請(qǐng)求,會(huì)嚴(yán)重消耗服務(wù)器資源。
gzip 如果某個(gè)文件存在gzip格式的文件(帶有g(shù)z后綴名的文件通常就在原始文件旁邊)。如果用戶代理支持 gzip 格式,并且啟用了該選項(xiàng),Tomcat 就會(huì)提供該格式文件的服務(wù)。默認(rèn)為 false。如果直接請(qǐng)求帶有 gz 后綴名的文件,是可以訪問(wèn)它們的,所以如果原始資源受安全挾制的保護(hù),則 gzip 文件也同樣是受保護(hù)的。
readmeFile 如果提供了目錄列表,那么可能也會(huì)提供隨帶的 readme 文件。這個(gè)文件是被插入的,因此可能會(huì)包含 HTML。
globalXsltFile 如果你希望定制目錄列表,你可以使用一個(gè) XSL 轉(zhuǎn)換)。這個(gè)值是一個(gè)可用于所有目錄列表的相對(duì)路徑文件名(既相對(duì)于 CATALINA_BASE/conf/ 也相對(duì)于 $CATALINA_HOME/conf/)。可參看下面介紹的 contextXsltFile 和 localXsltFile。該 xml 文件的格式會(huì)在下文介紹。
contextXsltFile 你可以通過(guò)contextXsltFile 來(lái)定制你的目錄列表。這必須是一個(gè)上下文相對(duì)路徑(例如:/path/to/context.xslt),相對(duì)于帶有 .xsl 或 .xslt 擴(kuò)展名的文件。它將覆蓋 globalXsltFile。如果提供了該值,但相對(duì)文件卻不存在,則將使用 globalXsltFile。如果 globalXsltFile 也不存在,則顯示默認(rèn)的目錄列表。
localXsltFile 你還可以在每個(gè)目錄通過(guò)配置 localXsltFile 定制你的目錄列表。它應(yīng)該是在產(chǎn)生列表的目錄里的一個(gè)相對(duì)路徑文件名。它覆蓋 globalXsltFile 和 contextXsltFile。如果該值存在,但是文件不存在,那么就使用 contextXsltFile。如果contextXsltFile 也不存在,那么就會(huì)使用 globalXsltFile。如果 globalXsltFile 也不存在,那么默認(rèn)的目錄列表就會(huì)被顯示出來(lái)。
showServerInfo 當(dāng)使用目錄列表,服務(wù)器信息是否應(yīng)該提供給發(fā)往客戶端的響應(yīng)中。默認(rèn)為 true。

上述來(lái)源:tomcat官網(wǎng)

看完上面的文檔,應(yīng)該對(duì)定制自己的目錄列表有一些思路了。
定制目錄列表需要自己定義globalXsltFile/contextXsltFile/localXsltFile,tomcat提供了定制的example。
話不多說(shuō),動(dòng)手吧,如果諸位看官需要對(duì)所有目錄進(jìn)行同樣的定制,那么可以采用globalXsltFile,如果跟格子一樣,只需要特定目錄下的,那么建議采用localXstlFile,先用tomcat提供的示例看下效果。
在特定目錄下(格子這里是$CALINA_BASE/webapps/zoro)下新建文件zoro.xslt(or .xsl后綴名要對(duì)),然后把下面的代碼拷貝進(jìn)去~

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0">

  <xsl:output method="html" html-version="5.0"
    encoding="UTF-8" indent="no"
    doctype-system="about:legacy-compat"/>

  <xsl:template match="listing">
   <html>
    <head>
      <title>
        Sample Directory Listing For
        <xsl:value-of select="@directory"/>
      </title>
      <style>
        h1 {color : white;background-color : #0086b2;}
        h3 {color : white;background-color : #0086b2;}
        body {font-family : sans-serif,Arial,Tahoma;
             color : black;background-color : white;}
        b {color : white;background-color : #0086b2;}
        a {color : black;} HR{color : #0086b2;}
        table td { padding: 5px; }
      </style>
    </head>
    <body>
      <h1>Sample Directory Listing For
            <xsl:value-of select="@directory"/>
      </h1>
      <hr style="height: 1px;" />
      <table style="width: 100%;">
        <tr>
          <th style="text-align: left;">Filename</th>
          <th style="text-align: center;">Size</th>
          <th style="text-align: right;">Last Modified</th>
        </tr>
        <xsl:apply-templates select="entries"/>
        </table>
      <xsl:apply-templates select="readme"/>
      <hr style="height: 1px;" />
      <h3>Apache Tomcat/<version-major-minor/></h3>
    </body>
   </html>
  </xsl:template>


  <xsl:template match="entries">
    <xsl:apply-templates select="entry"/>
  </xsl:template>

  <xsl:template match="readme">
    <hr style="height: 1px;" />
    <pre><xsl:apply-templates/></pre>
  </xsl:template>

  <xsl:template match="entry">
    <tr>
      <td style="text-align: left;">
        <xsl:variable name="urlPath" select="@urlPath"/>
        <a href="{$urlPath}">
          <pre><xsl:apply-templates/></pre>
        </a>
      </td>
      <td style="text-align: right;">
        <pre><xsl:value-of select="@size"/></pre>
      </td>
      <td style="text-align: right;">
        <pre><xsl:value-of select="@date"/></pre>
      </td>
    </tr>
  </xsl:template>

</xsl:stylesheet>

保存上面文件后,修改web.xml的神秘代碼

 <servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--看這里-->
        <init-param>
            <param-name>localXsltFile</param-name>
            <param-value>zoro.xslt</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

重啟tomcat,看效果


Tomcat目錄定制示例

是不是好了一些了,但是還是一般般,畢竟是官網(wǎng)提供的示例,也沒(méi)辦法漂亮到哪里去,不過(guò)定制的方法已經(jīng)提供,剩下的就是html美化了,各位可以自行發(fā)揮。

格子這邊用bootstrap的表格改了一版,如圖

基于Bootstrap美化的定制目錄

5、再啰嗦幾句

在進(jìn)行定制化的時(shí)候,難免有些特殊需求,雖然繁瑣但是還是可以實(shí)現(xiàn)的。
比如格子這邊需要對(duì)目錄進(jìn)行截取,可以在xslt文件中,利用substring函數(shù)來(lái)實(shí)現(xiàn)

 <xsl:variable name="urlPath" select="substring(@urlPath,12)"/>

當(dāng)然,還有很多其他的函數(shù),或者通過(guò)java/javasrcipt方式來(lái)擴(kuò)展,畢竟不是本文主題,不做贅述,需要的自行百度。

寫(xiě)在最后

好久沒(méi)寫(xiě)博客了,求捧場(chǎng),求點(diǎn)贊,求夸獎(jiǎng)。


yeah
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容