首先需要明确几容易混淆的规则:
1.精确匹配
配置的项必须与url完全精确匹配。
@WebServlet(urlPatterns ={"/HelloWorldServlet","/Haha","/Hehe"} ,loadOnStartup = 1)
假如上下文是http://localhost:8080/appDemo/
当在浏览器中输入如下几种url时,都会被匹配到该servlet http://localhost:8080/appDemo/HelloWorldServlet http://localhost:8080/appDemo/Haha ttp://localhost:8080/appDemo/Hehe
2.路径匹配
以“/”字符开头,并以“/*”结尾的字符串用于路径匹配。
@WebServlet(name = "TestServlet",value="/abc/*")
假如上下文是http://localhost:8080/appDemo/
当在浏览器中输入如下几种url时,都会被匹配到该servlet http://localhost:8080/appDemo/abc/HelloWorldServlet http://localhost:8080/appDemo/abc/haha/hello http://localhost:8080/appDemo/abc/haha/test.action
3.扩展名匹配
以“*.”开头的字符串被用于扩展名匹配
@WebServlet(name = "HelloServlet",value = "*.action")
假如上下文是http://localhost:8080/appDemo/
当在浏览器中输入如下几种url时,都会被匹配到该servlet http://localhost:8080/appDemo/welcome.action http://localhost:8080/appDemo/xixi/abc/hello.action http://localhost:8080/appDemo/test/haha/test.action
注意:路径匹配和扩展名匹配不可以同时使用,下面配置全是不合法的。
@WebServlet(name = "TestServlet",value="/abc/*.action")
@WebServlet(name = "TestServlet",value="/*.action")
注意:
@WebServlet(name = "DefaultServlet",value = "/")
会匹配到/login这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url
@WebServlet(name = "DefaultServlet",value = "/*")
会匹配所有url:路径型的和后缀型的url(包括/login,.jsp,.js和*.html等)
4.匹配优先级
当一个url与多个servlet的匹配规则可以匹配时,则按照 “ 完全匹配路径 > 最长路径>扩展名”这样的优先级匹配到对应的servlet