views:

457

answers:

1

I have defined several application parameters for my webapp in the web.xml file, as follows:

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

If I have a ServletContext Object object available, I can access them easily . For example in my Struts action classes.

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

How can I retrieve application parameters without passing ServletContext object around?

+1  A: 

Singleton + JNDI ?

You could declare your object as a resource in your webapp:

 <resource-ref res-ref-name='myResource' class-name='com.my.Stuff'>
        <init-param param1='value1'/>
        <init-param param2='42'/>
 </resource-ref>

Then, in your class com.my.stuff , you need a constructor and two "setters" for param1 and param2:

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;
         }
     }
}

Then, anywhere in your code:

...
com.my.Stuff.getInstance().getParam1();

Definitely overkill and sub-efficient, but it works (and can be optimised)

MatthieuP
As the question is tagged "tomcat": more info in http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html - Definitely the way to go. +1
Olaf