web-applications - 如何在不传递 ServletContext 对象的情况下检索应用程序参数?

标签 web-applications tomcat parameters

我在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/

相关文章:

java - Tomcat 类加载器 : priority between WebappX & Common

java - 需要帮助来理解和实现基本的 Web 应用程序安全性

java - 如何通过java发送自定义参数?

web-applications - 如何在没有 Web 服务器的情况下制作基于浏览器的应用程序?

google-apps-script - 在Google Apps脚本中停止错误 “Authorisation is required to perform that action”

c# - 从 C# 客户端在 Solr 中索引 pdf 文档

xslt - "context"关于调用模板参数的含义

java - 如何将/usr/share/java 库添加到 webapp 的类路径?

xml - Jsp 的 URL 映射

Java调用带有对象参数的方法到main方法