Tomcat 的 DefaultServlet

问题描述:

群里有人测试 Spring MVC,没有配置任何Controller,只配置了一个view resolver,指定了前缀后缀。

然后,他问的是 当访问 localhost:8080/test 的时候,为什么会被重定向到 localhost:8080/test/

由于是在Spring Boot群里问的,我想当然的认为 /test对应着Controller,于是百思不得其解。后来才知道不是Spring Boot项目,而是自己新建的一个maven项目,/test 对应着项目名称。

直觉告诉我,这肯定是Tomcat的默认行为,因为项目名称对应着文件夹,而 当访问一个文件夹的时候,默认会查找其中的 index.html 等index文件,重定向完全讲得通。

于是查找 tomcat(7.0.52)下面的配置文件,在 conf/web.xml 的末尾发现了这样的内容:

<!-- ==================== 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 files are present, the default servlet either serves a -->
  <!-- directory listing (see default servlet configuration on how to       -->
  <!-- customize) or returns a 404 status, depending on the value of the    -->
  <!-- listings setting.                                                    -->
  <!--                                                                      -->
  <!-- If you define welcome files in your own application's web.xml        -->
  <!-- deployment descriptor, that list *replaces* the list configured      -->
  <!-- here, so be sure to include any of the default values that you wish  -->
  <!-- to use within your application.                                       -->

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

这里说的就是:当一个请求URI对应一个目录时,default servlet会查找该目录下的欢迎文件;如果存在,则返回资源;如果不存在,那default servlet 要么返回目录列表(需要配置,默认不支持),要么返回 404 状态码。

但这里只是描述结果,并没有原理性的东西,想要知道原理 只能去查源代码。

根据上面的内容可以知道Tomcat 有一个default servlet,那我直接使用DefaultServlet查找相应的java文件(在IDEA中新建一个Spring Boot项目,再双击 Shift,输入DefaultServlet即可),果然找到了。

demo3

嗯嗯,这里的Tomcat 是8.5.x,Spring Boot 默认的版本,但DefaultServlet的原理一致。

原文地址:https://www.cnblogs.com/larryzeal/p/6751596.html