ServletContext setInitParameter的目的是什么?怎么用呢?

时间:2014-03-06 01:17:47

标签: java servlets

Servlet 3.0规范说:

setInitParameter

boolean setInitParameter(java.lang.String name,
                         java.lang.String value)

    Sets the context initialization parameter with the given name and value on this ServletContext.

    Parameters:
        name - the name of the context initialization parameter to set
        value - the value of the context initialization parameter to set 
    Returns:
        true if the context initialization parameter with the given name and value was set successfully on this ServletContext, and false if it was not set because this ServletContext already contains a context initialization parameter with a matching name 
    Throws:
        IllegalStateException - if this ServletContext has already been initialized 
        UnsupportedOperationException - if this ServletContext was passed to the ServletContextListener#contextInitialized method of a ServletContextListener that was neither declared in web.xml or web-fragment.xml, nor annotated with WebListener
    Since:
        Servlet 3.0

据我所知,在部署Web应用程序时会初始化servlet上下文。当我说,servletConfig.getServletContext().setInitParameter("email", "foo@bar.com")内部的servlet doGet()我得到IllegalStateException.

1 个答案:

答案 0 :(得分:8)

正如您在javadoc中看到的那样,如果您在初始化ServletContext之后尝试调用该方法,则会引发异常

  

IllegalStateException - 如果此ServletContext已初始化

在3.0之前的Servlet应用程序中,您可以使用以下配置设置上下文参数

<context-param>
    <param-name>some-param</param-name>
    <param-value>some-value</param-value>
</context-param>

这将设置一个上下文范围的参数,任何Servlet应用程序组件都可以访问它。

从3.0开始,您可以将部署配置移动到Java代码。通常,您将实现ServletContainerInitializer接口。 Servlet容器将找到您的实现,实例化它并执行其onStartup方法,将未初始化的ServletContext交给您。

然后,您可以使用setInitParameter方法设置上下文参数,就像在部署描述符中一样。当您的onStartup()方法返回时,Servlet容器会进一步处理以设置Web应用程序。完成后,它会初始化ServletContext,您的应用程序就可以处理请求了。

相关问题