Up to StrutsNewFaqs

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

Using a plug-in

Using a plug-in type class I believe should fit the bill here. This class is
executed upon application start-up. These values that you call or intialize
from whereever can be stored in application state for use by the rest of your

Your plug-in class should extend org.apache.struts.action.PlugIn. Once you
finish implementing the PlugIn interface, you would create an entry in your
strut-config.xml to reference the PlugIn that you just created.

You can find more information about it here:

You also might want to look at the JavaDocs for the PlugIn interface and read
up on that as well.

N.B. See also the StrutsPlugins page for other information on whether to use a PlugIn
or ServletContextListener.

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:


Define another servlet entry in web.xml


                log4j.appender.mylog.layout.ConversionPattern=%d{ddHHmmss MMM} %-5p %x - %m%n;                 


Use a ContextListener

In web.xml:


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 (smile)

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

  • No labels