How can I get application parameters without going through the ServletContext object?

I have defined several application parameters for my webapp in the web.xml file like this:

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

      

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

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

      

How to get application parameters without going through the ServletContext object?

0


source to share


1 answer


Singleton + JNDI?

You can declare your object as a resource in your web application:

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

      

Then, in your com.my.stuff class, 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 redundant and inefficient, but it works (and can be optimized)

+1


source







All Articles