問題描述:
群里有人測試 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即可),果然找到了。
嗯嗯,這里的Tomcat 是8.5.x,Spring Boot 默認的版本,但DefaultServlet的原理一致。