Spring MVC 在 web.xml 文件使用多个配置文件

更新时间:2021年02月23日

使用 Spring 的 ContextLoaderListener 加载 Web 应用程序上下文 XML 文件的方法。

方法:在 web.xml 的元素中配置 ContextLoaderListener 。

  • ContextLoaderListener 负责加载 contextConfigLoaction servlet 上下文初始化参数指定的根 Web 应用程序上下文 XML 文件。
  • <context-param>标签元素指定了 contextConfigLocation servlet 上下文初始化参数。
  • 在<param-value>标签元素中可以指定多个值[ classpath*: xml file path ],用逗号隔开。
  • 在 web.xml 文件中,标签元素的使用要遵从一定的次序,否则会报异常。
The content of element type "web-app" must match 
"(icon?,display-name?,description?,distributable?,context-param*,filter*,filter-mapping*,
listener*,servlet*,servlet-mapping*,session-config?,mime-mapping*,welcome-file-list?,error-page*,
taglib*,resource-env-ref*, resource-ref*,security-constraint*,login-config?,security-role*, 
env-entry*,ejb-ref*,ejb-local-ref*)"

配置文件:web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/META-INF/spring/appincationContext.xml</param-value>
    </context-param>

    <filter>...</filter>
    <filter-mapping>...</filter-mapping>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring/myapp-config.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

相关书籍:《Spring 学习指南(第四版)》Chapter 12
参考博客:https://www.cnblogs.com/lukelook/p/11071762.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值