JSP application design: where to set application-wide values [duplicate]

筅森魡賤 提交于 2019-12-11 14:25:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!