Up to StrutsNewFaqs


How to execute an initialization method before the first (web-)user interaction...


Using a plug-in


Define statics

Define statics (maybe even private with access methods) in your extended servlet.

public class yourActionServlet extends
{             org.apache.struts.action.ActionServlet 
    public void init() throws ServletException { 
        private static HashMap hashmap; 
        //read XML file into variable hashMap
    } 

    public static getHashMap(){
        return hashmap;
    }
}

Then from your actions, simply:

yourActionServlet.getHashMap();


Define another servlet entry in web.xml

{{{ <servlet>

}}}


Use a ContextListener

In web.xml:

<listener>
  <listener-class>my.app.MyContextListener</listener-class>
</listener>

Then, MyContextListener.java might be:

package my.app;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashMap;
public class MyContextListener implements ServletContextListener {
  private static HashMap myConfigData = new HashMap();
  public void contextInitialized(ServletContextEvent sce) {
    myConfigData.put("someKey", "someValue");
  }
  public void contextDestroyed(ServletContextEvent sce) { }
  public static Object getValue(String key) {
    return myConfigData.get(key);
  }
}

Then, in your code you can call MyContextListener.getValue("someKey"); to retrieve the value. Naturally, you probably want to do something more complex than this like reading from a config file and creating some "real" configuration holder object, but you get the point :)

Remember, you can do whatever you want here... it can be as simple or as complex as you like!

Note that there is an existing listener in the Java Web Parts project that will take care of all the details and allow you to just provide a configuration file. It creates a config object for you on-the-fly (and it also has more advanced capabilities if you require more control over things). Details at http://javawebparts.sourceforge.net in the Listener package.


Up to StrutsNewFaqs

StrutsInitialization (last edited 2009-09-20 23:12:43 by localhost)