Java - setting context attributes (ServletContextListener)
I read the properties file in the webapplication startup phase (contextInitialized ()) and I started thinking about how to make these settings "visible" to servlets. Do I need to iterate over the keys and add each one to a context like this
Iterator i = settings.keySet().iterator();
while (i.hasNext()) {
key = (String) i.next();
value = (String) settings.get(key);
context.setAttribute(key, value);
}
or are there better methods?
Thank!
/ Adam
Why not store all content in the context of a servlet?
context.setAttribute("mySettings", settings);
setAttribute signature:
public void setAttribute(String name, Object object)
Have you considered defining parameters in web.xml?
Also, if this is not possible, use generators if possible:
String key = null;
Iterator<String> i = settings.keySet().iterator();
while (i.hasNext())
context.setAttribute(key = i.next(), settings.get(key));
I thought with an idea:
In the context of an initialized method, I planned to create only one global object for settings. Very similar to the suggested toolkit. But instead of setting context attributes for every parameter / attribute / parameter, would it be a terrible idea to add a settings container / wrapper object? I think this class will be responsible for holding the (static?) Classes of module settings. This way I can get typed links like so
//ExampleServlet.java
Settings settings = (Settings)context.getAttribute("application.settings");
String color = settings.getModule1().getColor();
String font = settings.getModule1().getFont();
int blogs = settings.getModule2().getActiveBlogCount();
Throughout the code, I only need to remember one attribute , one for the entire settings container. Less risk of typos that can cause Roma exceptions! It will also make it easier to rename the attributes.
What do you think?
/ Adam
How about using JNDI context. JNDI is the more common way to pass properties to a website.
Any properties can be specified in the META-INF / context.xml file for tomcat or any specific application setting.
This is what I envisioned by setting the entire properties object as a context attribute.
If I don't go that route, is there any guidance on how to name these attributes, or do you feel like "application.settings" or "myBlog.settings"? How are you keys ? This will be good:
application.module1.color=black
application.module1.font=arial
I feel, in some way, that it can become a burden to maintain an application like this with property keys propagated throughout the code? If another developer renames a property in the properties file, we will only know when the application starts (if / when / what the old key refers to). Right?
I need to search for JNDI.