【问题标题】:Loading context in web.xml在 web.xml 中加载上下文
【发布时间】:2014-07-12 15:16:46
【问题描述】:

在上下文参数中加载上下文和在 Dispatcher Servlet 的 init-param 中加载上下文有什么区别。

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

<init-param>    
        <param-name>contextConfigLocation</param-name>    
        <param-value> /WEB-INF/mvc-config.xml </param-value>    
  </init-param> 

我的理解是 context-param 由上下文侦听器加载,并且应该只包含中间层 bean。 Dispatcher Servlet 在其 init 方法中应该加载 Web 层 bean。这种理解正确吗?为什么我们要分别加载 2 个东西?

【问题讨论】:

    标签: java spring servlets web.xml


    【解决方案1】:
    <context-param>
    
    • 写在&lt;Servlet&gt;标签外,在&lt;webapp&gt;标签内。
    • 贴花的值将可供整个应用程序使用
    • 应用程序中的任何 servlet(在 web.xml 中声明)都可以访问这些值
    • 因此,当我们希望在应用程序中的 servlet 之间共享相同的一组值(例如数据库配置详细信息)时,我们会使用它。
    • 可以使用ServletContext接口的public String getInitParameter(String name)方法获取值。
    • getServletContext()ServletConfig接口方法返回ServletContext对象。
    • GenericServlet 类的getServletContext() 方法返回ServletContext 的对象。
    • 示例 1:ServletContext application=getServletConfig().getServletContext();
    • 示例 2:ServletContext application=getServletContext();

    &lt;init-param&gt; .

    • 写在&lt;Servlet&gt;标签内。
    • 声明的值仅对 servlet 可用。
    • 可以使用ServletConfig接口的public String getInitParameter(String name)方法获取值。
    • Servlet接口getServletConfig()方法返回ServletConfig对象。
    • 示例:ServletConfig config=getServletConfig();

    【讨论】:

      【解决方案2】:

      在上下文参数“contextConfigLocation”中,您应该包含您的应用程序上下文,正如您已经说过的中间层 bean,例如:服务、数据源...

      Spring DispatcherServlet 将在 WEB-INF/servletName-servlet.xml 中查找配置文件。使用 init-param 您可以更改此默认行为。 servlet 上下文(Web 上下文)是隔离的,但可能会将应用程序上下文作为父级。您可以同时使用两者或其中之一。

      【讨论】:

        猜你喜欢
        • 2011-09-21
        • 2014-12-31
        • 2013-02-27
        • 1970-01-01
        • 1970-01-01
        • 2010-10-03
        • 2013-04-19
        • 2014-07-09
        • 1970-01-01
        相关资源
        最近更新 更多