web.xml中的上下文参数是什么?

时间:2014-08-07 04:30:06

标签: java-ee spring-mvc

<context-param>中的web.xml是什么?我们为什么要用它?

例如,以下是做什么的?

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet-servlet.xml</param-value>
</context-param>

3 个答案:

答案 0 :(得分:3)

在Spring Web应用程序中,contextConfigLocation上下文参数提供了根上下文的位置。

对于spring-mvc应用程序,

您的配置很奇怪,因为默认情况下为servletname-servlet.xml(其中servletnameDispatcherServlet servlet的名称)是servlet的子应用程序上下文。

当前(并且由Spring文档推荐)的是具有将包含模型层(服务,持久性和业务bean)的根上下文以及将包含控制器和视图层的servlet上下文(控制器,视图解析器) ,拦截器)。规则是servlet上下文中的bean可以使用根上下文的bean,但是倒数是假的。

答案 1 :(得分:2)

有时候你会想要设置一些参数并希望在整个web应用程序中访问它。然后是web.xml中指定的上下文参数发挥作用的时间。它有一个优势(以及通过web-app 的可用性),只需要在web.xml文件中进行更改,只要您想要更改该特定值。您可以指定context-param之类的

<servlet>
        <servlet-name>ServletName</servlet-name>
        <servlet-class>com.mypackage.MyServlet</servlet-class>
    </servlet>

    <context-param>
            <param-name>email</param-name>
            <param-value>myemail@email.com</param-value>
    </context-param>

可以像

一样访问它
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException{

        PrintWriter pw = response.getWriter();
        pw.println(getServletContext().getInitParameter("email"));

    }

答案 2 :(得分:1)

类似于键值对

它们可用于在Web应用程序的任何位置读取某些值

请参阅 http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/