Friday, July 23, 2010

Writing Your Own Struts PlugIn

A plugin is a configuration wrapper for a module-specific resource or service that needs to be notified about application startup and shutdown events." What this means is that you can create a class implementing the PlugIn interface to do something at application startup or shutdown like we want to initialize Hibernate as soon as the application starts up, so that by the time my web application receives the first request, Hibernate is already configured and ready to use. We also want to close down Hibernate when the application is shutting down. We write a plugin for this requirement with as Hibernate PlugIn.

1.Write a class implementing the PlugIn interface

      public class HibernatePlugIn implements PlugIn{
          private String configFile;
          // This method will be called at application shutdown time
          public void destroy() {
              System.out.println("Entering HibernatePlugIn.destroy()");
              //Put hibernate cleanup code here
              System.out.println("Exiting HibernatePlugIn.destroy()");
          }
          //This method will be called at application startup time
          public void init(ActionServlet actionServlet, ModuleConfig config)
              throws ServletException {
              System.out.println("Entering HibernatePlugIn.init()");
              System.out.println("Value of init parameter " +
                                  getConfigFile());
              System.out.println("Exiting HibernatePlugIn.init()");
          }
          public String getConfigFile() {
              return name;
          }
          public void setConfigFile(String string) {
              configFile = string;
          }
      }

The class implementing PlugIn interface must implement two methods: init() and destroy(). init() is called when the application starts up, and destroy() is called at shutdown. Struts allows you to pass init parameters to your PlugIn class. For passing parameters, you have to create JavaBean-type setter methods in your PlugIn class for every parameter. In our HibernatePlugIn class, I wanted to pass the name of the configFile instead of hard-coding it in the application.

2.Integrate this class with Struts by adding these lines to struts-config.xml:
      <\struts-config>
          ...
         
          <\message-resources parameter=
                "sample1.resources.ApplicationResources"/>
         
          <\plug-in className="com.sample.util.HibernatePlugIn">
              <\set-property property="configFile"  value="/hibernate.cfg.xml"/>
         
     

The className attribute is the fully qualified name of the class implementing the PlugIn interface. Add a element for every initialization parameter which you want to pass to your PlugIn class.

No comments:

Post a Comment