我在web.xml文件中为我的webapp定义了几个应用参数,如下:
<context-param>
<param-name>smtpHost</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
如果我有可用的 ServletContext Object 对象,我可以很容易地访问它们。例如在我的 Struts Action 类中。
ServletContext ctx = this.getServlet().getServletContext();
String host = ctx.getInitParameter("smtpHost");
如何在不传递 ServletContext 对象的情况下检索应用程序参数?
最佳答案
单例 + JNDI ?
您可以在您的网络应用程序中将您的对象声明为资源:
<resource-ref res-ref-name='myResource' class-name='com.my.Stuff'>
<init-param param1='value1'/>
<init-param param2='42'/>
</resource-ref>
然后,在您的类 com.my.stuff 中,您需要一个构造函数和两个参数 1 和参数 2 的“setter”:
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();
绝对是矫枉过正和效率低下,但它有效(并且可以优化)
关于web-applications - 如何在不传递 ServletContext 对象的情况下检索应用程序参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/406534/