问题
In a Java web application, where is the best place to set (or best mechanism to use in setting) a string (or strings) for use, application-wide, which should never change while the application is running, and most likely never after it is installed on a given server?
One thing that would be key in this is that I want to be able to access it anywhere (in a Java Class -OR- in a JSP), as this would be for things like an application name, URL, address, telephone number, etc.
I believe the "easiest" would be to use application.setAttribute() in every single JSP (or perhaps in a global include file or such), but this hardly makes sense, as it never changes - why keep setting it? However, setting it in the application context would offer the ability to use EL expressions or application.getAttribute() to retrieve the value - is there a better way or a better place to set attributes like this? somehow in web.xml? not sure why it's so hard to find... maybe I just don't know the question to ask Google.
回答1:
Use a ServletContextListener.
@WebListener
public class Config implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
Data data = createItSomehow();
event.getServletContext().setAttribute("data", data);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}
}
It'll be available in EL scope by ${data}.
来源:https://stackoverflow.com/questions/9604398/jsp-application-design-where-to-set-application-wide-values