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.
source share