7

Why would we set ServletContext parameters using the setAttribute() method, as we can accomplish the same thing by setting parameters in web.xml and fetching them using getInitParameter()?

hopper
  • 13,060
  • 7
  • 49
  • 53
Jayesh
  • 6,047
  • 13
  • 49
  • 81

1 Answers1

18

The servletContext.setAttribute() is dynamic which can be set and reset during runtime.

Where as init-parameter specified in web.xml is static which will not change during the lifetime of application.

Example:

  • The database properties like database name configuration propety. It will be mostly configured as context init-param
  • And if you want to set property value which derives based on runtime changes, like "last user logged in" or "number of failures" should be context attributes.
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
  • For Servlet 2.5, would the ServletContext.getInitParameter() return the same attribute set by ServletContext.setAttribute() ? – Gaurav Aug 22 '19 at 09:28