Up to StrutsNewFaqs
How to execute an initialization method before the first (web-)user interaction
Answers
{{{ = #1 Using a Servlet Context Listener =
- Define the Servlet Context Listener in the web.xml.
<listener>
<listener-class>
com.myCompany.MyServletContextListener
</listener-class>
</listener>
Create your MyServletContextListener class implementing the javax.servlet.ServletContextListener interface and put your initialization code in the contextInitialized() method. }}}
{{{ = #2 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 application.
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:
http://jakarta.apache.org/struts/userGuide/configuration.html#plugin_config
You also might want to look at the JavaDocs for the PlugIn interface and read up on that as well. }}}
#3 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
- return hashmap;
} }
Then from your actions, simply:
yourActionServlet.getHashMap();
#4 Define another servlet entry in web.xml
{{{ <servlet>
<servlet-name>
- myInit
</servlet-name> <servlet-class>
com.myCompany.MyServlet
</servlet-class>
<init-param>
<param-name>
- config
</param-name> <param-value>
- db.driver=org.gjt.mm.mysql.Driver; db.username=root; db.password=rootWasHere$; db.maxconnect=10; db.minconnect=1; db.url=jdbc:mysql://localhost/idmt; log4j.rootCategory=ERROR,mylog;
log4j.appender.mylog=org.apache.log4j.FileAppender; log4j.appender.mylog.File=System.err; log4j.appender.mylog.layout=org.apache.log4j.PatternLayout; log4j.appender.mylog.layout.ConversionPattern=%d{ddHHmmss MMM} %-5p %x - %m%n;
</param-value>
</init-param>
<load-on-startup>
- 1
</load-on-startup>
</servlet> }}}
Up to StrutsNewFaqs