Sotirios Delimanolis Sotirios Delimanolis - 1 year ago 148
Java Question

ServletContext or Properties class

I'm developing a Servlet that has different operations that depend on different parameters, say default values. However, I want to be able to change these values at run-time, through a jsp or command-line interface. Also, there are many different classes (mostly commands for each operation) that need to be able to access these parameters. Should I be storing these values in a bean MyProperties class that wraps java's Properties class to load up the values from a file and then change them? Or should I load them into the servlet's application context and get/set them from there?

Answer Source

Do both. Create and put the MyProperties class in the servlet context once on application's startup in ServletContextListener#contextInitialized(). Then you can get the stored instance from the servlet context in every servlet and JSP the usual way and retrieve/manipulate the properties through the MyProperties class accordingly.

This way you end up with only one attribute in the servlet context instead of countless attributes for each single property. This way you also don't need to fiddle with statics and singletons inside MyProperties which would not be abstractable or testable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download