在 Spring MVC 中添加 ContextLoaderListener 到 web.xml

2022-09-02 19:34:06

我是春季MVC的新手。我有一个 Web 应用程序。我有以下配置:

<welcome-file-list>
    <welcome-file>list.html</welcome-file>
</welcome-file-list>
<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


我是否需要将以下行添加到 web.xml 文件中?

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

答案 1

是的,仅当您要在加载应用程序时也加载其他Spring上下文xml文件时,才需要添加,并且可以将它们指定为ContextLoaderListenerweb.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring-security.xml
    </param-value>
</context-param>

答案 2

仅当您有两个配置 xml 文件时。一个带有服务/DAO,另一个带有控制器。如果你在一个 spring 配置文件中配置了所有内容,则不需要 ,只需调度程序 servlet 就足够了。ContextLoaderListener

建议将配置一分为二,并使用 创建根应用程序上下文,并使用调度程序 servlet 创建 Web 层应用程序上下文。ContextLoaderListener


推荐