将ContextLoaderListener添加到Spring MVC中的web.xml

问题描述 投票:18回答:5

我是Spring 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>
java spring spring-mvc
5个回答
26
投票

是的,你需要在ContextLoaderListener中添加web.xml,只有当你想在加载应用程序时加载其他Spring上下文xml文件时,你可以将它们指定为

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

15
投票

仅当您有两个config xml文件时。一个是Services / DAO,另一个是Controller。如果您在一个spring配置文件中配置了所有内容,则不需要ContextLoaderListener,只需调度程序servlet即可。

建议将配置拆分为两个,并使用ContextLoaderListener创建根应用程序上下文和调度程序servlet以创建Web层应用程序上下文。


5
投票

它是可选的,你真的不需要它只是为了Spring MVC(DispatcherServlet会这样做)。但是必须在Spring Spring上添加Spring安全性

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

只需一句话,如果使用ContextLoaderListener,你将不得不添加DelegatingFilterProxy

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

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/admin</url-pattern>
</filter-mapping>

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

在你的web.xml中也是如此。抱歉四年太晚了。干杯


3
投票
<servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml,WEB-INF/spring-security.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>UR_PATTERN</url-pattern>
    </servlet-mapping>

这对我来说很好。


0
投票

这可能有点高级,在我的应用程序(企业应用程序)中,他们构建自己的侦听器类并放入web.xml。在启动时,此自定义侦听器将扫描应用程序以收集所有信息,包括资源,外部连接,服务器信息ip,jar等。可以在网页中访问该信息。

© www.soinside.com 2019 - 2024. All rights reserved.