问题描述
在Java Web应用程序中,设置(或设置中使用的最佳机制)的最佳位置在哪里在整个应用程序范围内使用的一个或多个字符串,该应用程序正在运行,并且很可能永远不会在将其安装到给定服务器上之后出现?
对此很关键的一点是,我希望能够在任何地方(在JSP的Java类-OR-中)访问它,因为这将用于诸如应用程序名称,URL,地址,电话号码等
我相信最简单" 将是在每个JSP(或也许在全局包含文件等)中使用application.setAttribute()
,但这几乎没有道理,因为它永远不会改变-为什么继续设置它?但是,在应用程序 context 中进行设置将提供使用EL表达式或application.getAttribute()
检索值的功能-是否有更好的方法或更好的位置来设置这样的属性?不知何故在web.xml中?不知道为什么这么难找到...也许我只是不知道问Google的问题.
@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.
}
}
它将在${data}
的EL范围内可用.
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.
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}
.
这篇关于JSP应用程序设计:在何处设置应用程序范围的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!