How to configure <context-param> programmatically without web.xml
Asked Answered
T

2

8

Is there any other way to configure a context parameter excluding the one which uses web.xml as in the below example?

<context-param>
    <param-name>com.sun.faces.numberOfLogicalViews</param-name>
    <param-value>10</param-value>
</context-param>
Thibodeaux answered 13/7, 2016 at 10:7 Comment(1)
When is 'programmatically setting' required?Churlish
C
18

Since Servlet 3.0, you can programmatically set them via ServletContext#setInitParameter().

Just put below ServletContextListener anywhere in your web project. The @WebListener annotation will make the container to automatically pickup and run it during webapp startup.

@WebListener
public class Config implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext(); 
        servletContext.setInitParameter("com.sun.faces.numberOfLogicalViews", "10");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // NOOP.
    }

}
Covariance answered 13/7, 2016 at 10:41 Comment(2)
@Covariance how to set context-param programmatically for servlet 2.5?Surfeit
Upgrade to Servlet 3.0 or newer. It was released a decade ago already.Covariance
H
1

If you're using embedded Tomcat, it is like this:

Context.getServletContext()
    .getServletRegistrations()
    .get("webdavservlet")
    .setInitParameter("listings", "true");
Huttan answered 17/3, 2018 at 8:51 Comment(1)
how to set context-param programmatically for servlet 2.5?Surfeit

© 2022 - 2024 — McMap. All rights reserved.