I'm a bit confused with regards to the new setInitParameter(java.lang.String name, java.lang.String value) method of ServletContext.
Looking at the API, it says that this method "throws an IllegalStateException if this ServletContext has already been initialized". Now won't the ServletContext always be initialised before any Servlet is initialised? Does this mean you can't call setInitParameter() programmatically from within a Servlet??
Does this mean you can't call setInitParameter() programmatically from within a Servlet??
Yes, you can't (but Tomcat allows you to do it inside a Servlet...)
This method was added to the Servlet 3.0 in relation with the programmable interface:
4.4 Configuration methods The following methods are added to ServletContext since Servlet 3.0 to enable programmatic definition of servlets, filters and the url pattern that they map to. These methods can only be called during the initialization of the application either from the contexInitialized method of a ServletContextListener implementation or from the onStartup method of a ServletContainerInitializer implementation. In addition to adding Servlets and Filters, one can also look up an instance of a Registration object corresponding to a Servlet or Filter or a map of all the Registration objects for the Servlets or Filters. If the ServletContext passed to the ServletContextListener's contextInitialized method was neither declared in web.xml or webfragment.xml nor annotated with @WebListener then an UnsupportedOperationException MUST be thrown for all the methods defined for programmatic configuration of servlets, filters and listeners
4.4.1 Programmatically adding and configuring Servlets The ability to programmatically add a servlet to a context is useful for framework developers. For example a framework could declare a controller servlet using this method. The return value of this method is a ServletRegistration or a ServletRegistration.Dynamic object which further allows you to setup the other parameters of the servlet like init-params, url-mappings etc. There are three overloaded versions of the method as described below.
posted 7 years ago
I see... very clear explanation in the documentation, thanks a lot for posting that, Fritz.