Web applications 如何在不传递ServletContext对象的情况下检索应用程序参数?
我在web.xml文件中为我的webapp定义了几个应用程序参数,如下所示:Web applications 如何在不传递ServletContext对象的情况下检索应用程序参数?,web-applications,tomcat,parameters,Web Applications,Tomcat,Parameters,我在web.xml文件中为我的webapp定义了几个应用程序参数,如下所示: <context-param> <param-name>smtpHost</param-name> <param-value>smtp.gmail.com</param-value> </context-param> 如何在不传递ServletContext对象的情况下检索应用程序参数 Singleton+JNDI 您可以在web
<context-param>
<param-name>smtpHost</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
如何在不传递ServletContext对象的情况下检索应用程序参数 Singleton+JNDI
您可以在webapp中将对象声明为资源:
<resource-ref res-ref-name='myResource' class-name='com.my.Stuff'>
<init-param param1='value1'/>
<init-param param2='42'/>
</resource-ref>
然后,在代码中的任意位置:
...
com.my.Stuff.getInstance().getParam1();
肯定是杀伤力过大和效率低下,但它是有效的(并且可以优化)因为问题被标记为“tomcat”:更多信息进来-肯定是要走的路+1.
package com.my;
import javax.naming.*;
public class Stuff
{
private String p;
private int i;
Stuff(){}
public void setParam1(String t){ this.p = t ; }
public void setParam2(int x){ this.i = x; }
public String getParam1() { return this.p; }
public String getParam2(){ return this.i; }
public static Stuff getInstance()
{
try
{
Context env = new InitialContext()
.lookup("java:comp/env");
return (UserHome) env.lookup("myResource");
}
catch (NamingException ne)
{
// log error here
return null;
}
}
}
...
com.my.Stuff.getInstance().getParam1();