3

If I had to define a context-visib parameter at runtime, I wouldn't use ServletContext.setInitParameter() because init parameters are defined in the deployment descriptor once for all, and I suppose that ServletContext().setAttribute() would be more appropriate.

Said that,

  1. is my approach correct? In which case should I use ServletContext.setInitParameter() instead of ServletContext().setAttribute()?
  2. why is the method called setInitParameter()? Init parameters are actually defined for ServletConfig in the web.xml file, I'm setting/getting context parameters (owning to ServletContext) instead.
Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48

1 Answers1

1
  1. Yes, your approach is correct. Using ServletContext::setAttribute is the correct way to do what you're doing. If you look at the javadoc for ServletContext::setInitParameter, you'll see it says:

IllegalStateException - if this ServletContext has already been initialized

So once the context has started up, you won't be able to call that method any more.

  1. setInitParameter was introduced with Servlet 3.0, which introduces annotation-based config as an alternative to XML config. I assume this method was added to allow annotation-based config to populate the init params via a Java method call.
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • At this point I'm a bit confused... Inside a Servlet i can call *getServletContext().setInitParameter("e-mail","e-mail@email.com")* without getting an exception, but isn't the context already initialized at that stage? – Luigi Cortese Apr 15 '15 at 08:53