JSP application design: where to set application-w

2019-09-05 04:22发布

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条回答
我命由我不由天
2楼-- · 2019-09-05 04:45

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}.

查看更多
登录 后发表回答