ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# Tomcat – 启用/禁用目录列表 > 原文: [https://howtodoinjava.com/tomcat/tomcat-enabledisable-directory-listing/](https://howtodoinjava.com/tomcat/tomcat-enabledisable-directory-listing/) 当您的应用部署在 **tomcat** Web 服务器中,并且您请求指向目录而不是文件的 URL(例如`http://host:port/helloWorldApp/`)时,您可以**将 Tomcat 配置为提供目录列表**或欢迎文件,或发出错误“404 页面未找到”。 让我们看看如何**启用或禁用 tomcat 服务器**中的目录列表。 ```java Table of Contents Enabling Directory Listing for ALL Webapps Enabling Directory Listing for any particular Webapp ``` ## 为所有 Webapp 启用目录列表 要为所有 Web 应用启用目录列表,您可以通过将“`default`” servlet 的“`listings`”从“`false`”更改为“`true`”来修改`<CATALINA_HOME>\conf\web.xml`,如下所示: ```java <!-- 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. --> <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> <load-on-startup>1</load-on-startup> </servlet> <!-- The mapping for the default servlet --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- ==================== Default Welcome File List ===================== --> <!-- When a request URI refers to a directory, the default servlet looks --> <!-- for a "welcome file" within that directory and, if present, --> <!-- to the corresponding resource URI for display. If no welcome file --> <!-- is present, the default servlet either serves a directory listing, --> <!-- or returns a 404 status, depending on how it is configured. --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> ``` 上面的配置将 URL “`/`”(Web 上下文的根目录)映射到 Java 类`DefaultServlet`。 我们**通过将 Servlet 的初始化参数`listings`更改为`true`来启用目录列表**。 如果用户请求目录,并且目录列表已启用并且包含`<welcome-file>`列表中的文件之一,则将提供欢迎文件; 否则,将提供目录列表。 另一方面,如果接收到目录请求且未启用目录列表,则服务器将返回错误“404 页面未找到”。 ## 为任何特定的 Webapp 启用目录列表 如果只希望允许特定 Web 应用的目录列表,则可以全局禁用“`<CATALINA_HOME>\conf\web.xml`”中的目录列表,并在特定于应用的`WEB-INF\web.xml`中定义以下`<servlet>`和`<servlet-mapping>`,如下所示 : ```java <servlet> <servlet-name>DirectoryListing</servlet-name> <servlet-class>com.package.MyServlet</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> </servlet> <servlet-mapping> <servlet-name>DirectoryListing</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` 请注意,启用**目录列表**对于测试服务器很方便,但对于生产服务器则不希望。 **祝您学习愉快!**