Servlet资源要想被访问到,必须有访问路径,可通过两种方式去设置访问方式。
一、通过urlPatterns设置访问路径,而访问路径的书写又有多种格式,就又涉及到urlPatterns匹配规则,下面介绍常见的四种。
1、精确路径匹配
是一个具体路径,优先级最高。
配置路径:
@WebServlet("/user/select")
访问路径:
localhost:8080/web-demo/user/select
2、目录匹配
以/开头,以/*结尾,优先级第二。
配置路径:
@WebServlet("/user/*")
访问路径:
localhost:8080/web-demo/user/nihao
//或者
localhost:8080/web-demo/user/bao
当目录匹配/user下自己写的名字刚好和精确路径匹配中的名字一样时会访问哪个Servlet资源?
答案是精确路径匹配,因为精确路径匹配的优先级最高。
/*就属于路径匹配特殊的一种。?不明白。
3、扩展名匹配
*.扩展名,如*.do、*.jsp,优先级第三。
配置路径:
@WebServlet("*.do")
访问路径:
localhost:8080/web-demo/aaa.do
localhost:8080/web-demo/bbb.do
我觉得*就代表任意字符串。
注:扩展名方式匹配的时候开头部分没有/(斜杠),如果添加了/,那么就会出现一个异常。
4、缺省匹配
配置路径:
@WebServlet("/")
@WebServlet("/*")
访问路径:
localhost:8080/web-demo/hehe
servlet的url-pattern匹配规则,包括/和/*区别_addurlpatterns默认-优快云博客
关于第四种,后面再说吧,看不懂。
使用/和/*实现任意匹配的区别:
url-pattern配置为"/"和"/*"的区别-优快云博客
原文链接:https://blog.youkuaiyun.com/m0_57001006/article/details/125718822
二、通过xml文件配置Servlet访问路径
在web.xml文件中配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--
Servlet 全类名
-->
<servlet>
<!-- servlet的名称,名字任意-->
<servlet-name>demo13</servlet-name>
<!--servlet的类全名-->
<servlet-class>com.itheima.web.ServletDemo13</servlet-class>
</servlet>
<!--
Servlet 访问路径
-->
<servlet-mapping>
<!-- servlet的名称,要和上面的名称一致-->
<servlet-name>demo13</servlet-name>
<!-- servlet的访问路径-->
<url-pattern>/demo13</url-pattern>
</servlet-mapping>
</web-app>