最近在看小碼哥公開課的時(shí)候论颅,有幸遇到翻車現(xiàn)場(chǎng)。先還原下現(xiàn)場(chǎng)環(huán)境:
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Spring MVC配置如上攀唯,導(dǎo)致jsp無法渲染。
于是內(nèi)心產(chǎn)生這么一個(gè)疑問,到底配置成/與/*有什么區(qū)別噪窘?為何會(huì)導(dǎo)致jsp無法渲染?
回答上面問題前禾唁,我們先介紹下相關(guān)知識(shí)效览。
一、servlet的url-pattern的四種匹配規(guī)則
1. 精確匹配
<url-pattern>中配置的項(xiàng)必須與url完全精確匹配
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/user/users.html</url-pattern>
<url-pattern>/index.html</url-pattern>
<url-pattern>/user/addUser.action</url-pattern>
</servlet-mapping>
2.路徑匹配
以“/*”結(jié)尾的字符串用于路徑匹配
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/user/*</url-pattern>
</servlet-mapping>
3.擴(kuò)展名匹配
以“*.”開頭的字符串被用于擴(kuò)展名匹配
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
4.缺省匹配
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
四種匹配規(guī)則的優(yōu)先級(jí)是 1 > 2 > 3 > 4荡短。其中需要注意的是路徑匹配和擴(kuò)展名匹配無法同時(shí)設(shè)置丐枉,如<url-pattern>/user/*.action</url-pattern>
是非法的,<url-pattern>/aa/*/bb</url-pattern>
是精確匹配
二、Tomact中web.xml的默認(rèn)配置
<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>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- The mappings for the JSP servlet -->
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspx</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
Tomact啟動(dòng)時(shí)是默認(rèn)添加了對(duì)jsp的映射處理掘托,如果在springMVC中配置了/*的匹配規(guī)則瘦锹,按照匹配的順序,所有請(qǐng)求都無法再映射到默認(rèn)的jsp的servlet中了闪盔,從而導(dǎo)致jsp無法渲染