This is a rather long-winded, general question, regarding best practice. I'm curious as to how best to share ServletContext attributes with other layers of an MVC2 application - particularly the model. I know application.getAttribute(...) can be used from within a
JSP, but consider this scenario:
I have a MyService object that relays information between MyServlet and MyDataAccessObject. MyDataAccessObject runs queries and updates etc.. against a database using
Context ctx = new InitialContext();
DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/myDB");
//more stuff
The DB information is configured in
Tomcat 4.1's server.xml file using <ResourceParam> tags etc...
So far, so good - nothing unusual. But what if I want that lookup key -
java:comp/env/jdbc/myDB - to be part of the configuration for my application so it's not tied to a particular
Servlet Container, DataBase platform, or anything else - essentially extensible? If I store it as a ServletContext attribute, how do I get that ServletContext down to the DAO, without passing it along through all the layers so it can lookup that DB info? I initially wrote a servlet class called ApplicationProperties that had an instance method:
Object getapplicationProperty(
String propertyName)
{
ServletContext ctx = getServletContext();
return ctx.getAttribute(propertyName);
}
I overrode init(ServletConfig config) in this servlet and had it <load-on-startup>. I'd then be able to call:
ApplicationProperties.getInstance().getApplicationProperty(propertyName);
from anywhere within my app, but I don't really like this implementation - I can't make this a Singleton class, because I can't have a private constructor (due to the Tomcat needing to create one instance of it - I think...), it seems to only work when it wants to (getServletContext() in getApplicationProperty() sometimes returns null for some strange reason) and I have a nagging feeling that there's a better way to do this. I'm thinking a java.util.Properties file, but not certain. Anyway - sorry for the long post - any ideas are helpful. Thanks!
[ August 12, 2003: Message edited by: Brian Wainwright ]