【问题标题】:How can I retrieve application parameters without passing ServletContext object around?如何在不传递 ServletContext 对象的情况下检索应用程序参数?
【发布时间】:2010-09-29 05:22:11
【问题描述】:

我在web.xml文件中为我的webapp定义了几个应用参数,如下:

<context-param>
    <param-name>smtpHost</param-name>
    <param-value>smtp.gmail.com</param-value>
</context-param>

如果我有一个可用的 ServletContext Object 对象,我可以轻松访问它们。例如在我的 Struts 动作类中。

ServletContext ctx = this.getServlet().getServletContext();
String host = ctx.getInitParameter("smtpHost");

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

【问题讨论】:

    标签: web-applications tomcat parameters


    【解决方案1】:

    单例 + 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 中,您需要一个构造函数和两个用于 param1 和 param2 的“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();
    

    绝对是矫枉过正且效率低下,但它有效(并且可以优化)

    【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    相关资源
    最近更新 更多