了解web.xml

参考:https://www.cnblogs.com/roy-blog/p/7656834.html

web容器读取web.xml文件,配置文件的加载顺序:

    3.1、context-param

    3.2、listener

    3.3、filter

    3.4、servlet

二、细节

1、context-param:web应用servlet上下文初始化参数的声明。

2、listener:用来注册一个监听器类。事件监听程序在以下情况时通知

    ①应用的启动和关闭;

    ②session的创建与销毁,属性的新增、移除和更改;    

    ③对象被绑定到session中或从session中删除;

3、filter:过滤器,就是对请求进行过滤,filter也会在项目启动的时候被实例化。一般一个filter要对应filter-mapping,用于筛选所要执行过滤器中代码的url路径。如果一个filter没有filter-mapping,那它存在的意义就不大,它在web.xml存在的目的纯粹就是为了在项目启动的时候被实例化,从而执行其内部的代码。

三、一个简单的web.xml文件详解

xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

id="WebApp_ID" version="3.1">

    contextConfigLocation

    classpath:applicationContext.xml

    

        org.springframework.web.context.ContextLoaderListener

    

    encoding

    

        org.springframework.web.filter.CharacterEncodingFilter

    

    

        encoding

        UTF-8

    

    encoding

    *.action

    springmvc

    

        org.springframework.web.servlet.DispatcherServlet

    

    

        contextConfigLocation

        classpath:springmvc-config.xml

    

    1

    springmvc

    *.action

1、如果在web.xml中不写任何参数配置信息,默认的路径是/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml;contextConfigLocation 定义了要装入的 Spring 配置文件,通过ContenxtLoarderListener实现。

2、ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。

3、DispatcherServlet:一个特殊的servlet,是整个spring mvc框架的核心,他是一个前端servlet,spring mvc经过前端servlet来接受所有的请求,然后再讲具体工作派发给其他的的servlet来具体实现。同时,名为springmvc的servlet读取了contextConfigLocation所定义的配置文件(classpath:ApplicationContext-mvc.xml),启动了web层的spring容器,在这个容器里,我们初始化了所有的controller类。

4、把DispatcherServlet首先加载的原因:由于初始化DispatcherServlet伴随着启动spring mvc容器,所以需要较长的时间,所以我们希望在项目启动的时候就进行初始化的操作。因为这个属性设为正数的表示在项目启动的时候就初始化,数字越小表明越早初始化。如果我们将其设为负数的话。那么在项目启动的时候,将不会启动spring mvc的容器,而是当我们第一次访问某个controller所对应的action的时候才来加载启动容器,这将会造成较长时间的等待,所以我们一般将load-on-startup设为1。

5、context-param与init-param区别

    5.1、init-parm配置在标签中,用来初始化当前的Servlet的,属于当前Servlet的配置。

    5.2、context-param直接配置在web.xml的标签中,属于上下文参数,在整个web应用中都可以使用,它是全局的。

你可能感兴趣的:(了解web.xml)