一、首先web.xml配置文件是非必须的,如果你的web项目没有servlet、filter等的配置的时候,当然是不需要web.xml的配置文件。web.xml配置文件是用来初始化项目的配置的,比如Welcome页面、servlet、servlet-mapping、filter、listener、启动加载级别等。
二、servlet的配置
<?xml version="1.0" encoding="UTF-8"?>
<!--该xml配置文件遵循的模式定义,也就是标签规则模式-->
<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-name>servletTest</servlet-name>
<!--一定是package + .类名,项目中定位该servlet的完整路径。-->
<servlet-class>com.lmm.test.ServletTest</servlet-class>
</servlet>
<!--给Servlet提供(映射)一个可供客户端访问的URI,浏览器访问该servlet要访问的url定义-->
<servlet-mapping>
<!--和servlet中的name必须相同-->
<servlet-name>servletTest</servlet-name>
<!-- servlet的映射路径 客户端访问url -->
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
</web-app>
以上定义之后,浏览器访问 http://ip:port/servlet 即可访问项目中com.lmm.test.ServletTest类。走其中的业务逻辑。
补充:mapping匹配规则的配置
精确匹配 | /servlet | http://localhost:8080/day10/servlet |
模糊匹配 | /* | http://localhost:8080/20170323/任意路径 |
/lm/* | http://localhost:8080/20170323/lm/任意路径 | |
*.后缀名 如下: *.do *.action *.html(伪静态) |
http://localhost:8080/20170323/任意路径.do |
注意:优先级从高到低:绝对匹配、/开头匹配 、扩展名方式匹配
1)url-pattern要么以 / 开头,要么以*开头。 绝对不能漏掉斜杠!!!!!!!!!
2)不能同时使用两种模糊匹配,例如 /lm/*.do是非法路径
3)当有输入的URL有多个servlet同时被匹配的情况下:
3.1 精确匹配优先。(长的最像优先被匹配)
3.2 以后缀名结尾的模糊匹配先级最低!!!
web.xml的加载顺序是什么?
首先可以肯定的是,加载顺序与它们在 web.xml 文件中的先后顺序无关。即不会因为 filter 写在 listener 的前面而会先加载 filter。最终得出的结论是:ServletContext(context-param) -> listener -> filter -> servlet