【问题标题】:Adding ContextLoaderListener to web.xml in Spring MVC在 Spring MVC 中将 ContextLoaderListener 添加到 web.xml
【发布时间】:2012-06-16 09:43:16
【问题描述】:

我是 Spring MVC 的新手。我有一个网络应用程序。我有以下配置:

<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


【解决方案1】:

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

【讨论】:

  • Springboot Actuator 的工作与我上面描述的自定义相同。
【解决方案2】:

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

建议将配置一分为二,使用ContextLoaderListener创建根应用上下文,使用dispatcher servlet创建web层应用上下文。

【讨论】:

    【解决方案3】:

    它是可选的,你真的不需要它来仅仅用于 Spring MVC(DispatcherServlet 可以)。但是向 Spring MVC 添加 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 中。抱歉晚了四年。干杯

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-06-12
        • 2014-03-01
        • 2022-01-11
        • 2012-09-01
        • 1970-01-01
        • 2012-12-12
        • 2013-12-15
        • 1970-01-01
        • 2011-12-27
        相关资源
        最近更新 更多