web.xml的加载顺序及spring+springmvc的web.xml配置

本文详细解析了web.xml配置文件中的加载顺序,包括context-param、listener、filter和servlet的加载过程。重点介绍了Spring提供的ContextLoaderListener如何自动装载ApplicationContext配置信息,并说明了如何自定义配置文件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 web.xml中配置的加载优先级context-param -> listener -> filter -> servlet

1.context-param,它用于向 ServletContext 提供键值对,即应用程序上下文信息。我们的 listener, filter 等在初始化时会用到这些上下文中的信息所以context-param最先加载

2.Listener加载

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Spring提供ServletContentListener的一个实现类ContextLoaderListener监听器,该类可以作为Listener使用,在启动Tomcat
容器的时候,该类的作用就是自动装载ApplicationContext的配置信息,如果没有设置contextConfigLocation的初始参数则会
使用默认参数WEB-INF路径下的application.xml文件。如果需要自定义读取多个配置文件或者修改默认路径,则可以在web.xml
中设置: 

3. filter加载

4.servlet加载

 <!--前端控制器-->
    <servlet>
        <!--这里的名字应和前端容器的配置文件的名字一样,后面的“-servlet.xml”编译器自动补齐-->
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </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_3_1.xsd"
         version="3.1"
         metadata-complete="true">
    <!--监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--根容器/上下文容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <!--前端控制器-->
    <servlet>
        <!--这里的名字应和前端容器的配置文件的名字一样,后面的“-servlet.xml”编译器自动补齐-->
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值