servlet-mapping /与/*到底何意?

2019-08-13  本文已影响0人  Hogantry

最近在看小码哥公开课的时候,有幸遇到翻车现场。先还原下现场环境:

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

Spring MVC配置如上,导致jsp无法渲染。

于是内心产生这么一个疑问,到底配置成/与/*有什么区别?为何会导致jsp无法渲染?

回答上面问题前,我们先介绍下相关知识。

一、servlet的url-pattern的四种匹配规则

1. 精确匹配

<url-pattern>中配置的项必须与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.路径匹配

以“/*”结尾的字符串用于路径匹配

<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/user/*</url-pattern>
</servlet-mapping>

3.扩展名匹配

以“*.”开头的字符串被用于扩展名匹配

<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>

四种匹配规则的优先级是 1 > 2 > 3 > 4。其中需要注意的是路径匹配和扩展名匹配无法同时设置,如<url-pattern>/user/*.action</url-pattern>是非法的,<url-pattern>/aa/*/bb</url-pattern>是精确匹配

二、Tomact中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>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启动时是默认添加了对jsp的映射处理,如果在springMVC中配置了/*的匹配规则,按照匹配的顺序,所有请求都无法再映射到默认的jsp的servlet中了,从而导致jsp无法渲染

Servlet容器Tomcat中web.xml中url-pattern的配置详解[附带源码分析]

上一篇 下一篇

猜你喜欢

热点阅读