servlet的url-pattern匹配规则
首先需要明确几容易混淆的规则:
1 .servlet容器中的匹配规则既不是简单的通配,也不是正则表达式,而是特定的规则。所以不要用通配符或者正则表达式的匹配规则来看待servlet的url-pattern。
- Servlet 2.5开始,一个servlet可以使用多个url-pattern规则,<servlet-mapping>标签声明了与该servlet相应的匹配规则,每个<url-pattern>标签代表1个匹配规则;
- 当servlet容器接收到浏览器发起的一个url请求后,容器会用url减去当前应用的上下文路径,以剩余的字符串作为servlet映射,假如url是http://localhost:8080/appDemo/index.html,其应用上下文是appDemo,容器会将http://localhost:8080/appDemo去掉,用剩下的/index.html部分拿来做servlet的映射匹配
- url-pattern映射匹配过程是有优先顺序的
5.而且当有一个servlet匹配成功以后,就不会去理会剩下的servlet了。
1 精确匹配
<url-pattern>中配置的项必须与url完全精确匹配。
当在浏览器中输入如下几种url时,都会被匹配到该servlet
http://localhost:8080/appDemo/user/users.html
http://localhost:8080/appDemo/index.html
http://localhost:8080/appDemo/user/addUser.action
注意:
http://localhost:8080/appDemo/user/addUser/
是非法的url,不会被当作http://localhost:8080/appDemo/user/addUser识别
另外上述url后面可以跟任意的查询条件,都会被匹配,如
http://localhost:8080/appDemo/user/addUser?username=Tom&age=23 会被匹配到MyServlet。
2 路径匹配
以“/”字符开头,并以“/*”结尾的字符串用于路径匹配
路径以/user/开始,后面的路径可以任意。比如下面的url都会被匹配。
http://localhost:8080/appDemo/user/users.html
http://localhost:8080/appDemo/user/addUser.action
http://localhost:8080/appDemo/user/updateUser.actionl
3 扩展名匹配
以“*.”开头的字符串被用于扩展名匹配
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
则任何扩展名为jsp或action的url请求都会匹配,比如下面的url都会被匹配
http://localhost:8080/appDemo/user/users.jsp
http://localhost:8080/appDemo/toHome.action
4 缺省匹配
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>