Is there a way to add a context-param programmatically? I don't want to add in the web-xml. Specifically I want to do what the answer in this post suggests: Invoking methods with parameters by EL in JSF 1.2.
Asked
Active
Viewed 4,900 times
1 Answers
9
Yes it is possible.
In the servlet's init method, use
getServletConfig().getServletContext().setInitParameter("[Parameter name]", "[value]");
OR simply
getServletContext().setInitParameter("[Parameter name]", "[value]");
This must do the trick for you.
For the application load,
In web.xml, when you declare this servlet, provide <load-on-startpup>
element as 1 for this servlet.
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Ravindra Gullapalli
- 9,049
- 3
- 48
- 70
-
2This approach will however not guarantee that the API which needs the context parameter in question will read it *after* it is programmatically been set. – BalusC Jan 28 '12 at 05:07
-
It will because the programmer knows the first servlet that will be loaded in the application and in that servlet, init parameters will be set. – Ravindra Gullapalli Jan 28 '12 at 07:02
-
5Some APIs (like JSF!) use `ServletContextListener` or `ServletContainerInitializer` to initialize the API and they run long before the first `Servlet` is created. – BalusC Jan 28 '12 at 15:33
-
So maybe a `ServletContextListener` or the other is the best place to set init parameters? – Jaime Hablutzel Apr 05 '14 at 06:16
-
By the way `setInitParameter` seems to be only available from Servlet 3.0 onwards – Jaime Hablutzel Apr 06 '14 at 01:52