What is the purpose of the ServletContext setInitParameter? How can I use it?

The Servlet 3.0 specification states:

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 

As I understand it, the servlet context is initialized when the web application is deployed. When I say servletConfig.getServletContext().setInitParameter("email", " foo@bar.com ") inside the doGet () servlet, I get an IllegalStateException.

+6
source share
1 answer

As you can see in javadoc, an exception is thrown if you try to call a method after initializing ServletContext

IllegalStateException - if this ServletContext is already initialized

In servlet version 3.0 applications, you can set context parameters with the following configuration

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

This will set the context parameter that any component of the Servlet application can access.

Starting with version 3.0, you can port the deployment configuration to Java code. Typically, you implement the ServletContainerInitializer interface. The Servlet container will find your implementation, instantiate and execute the onStartup method, passing you the uninitialized ServletContext .

You can then use the setInitParameter method to set context parameters, as you would in a deployment descriptor. When your onStartup() method returns, the Servlet container does further processing to configure the web application. When this is done, it will initialize the ServletContext , and your application will be ready to work and process requests.

+6
source

All Articles