"Bailey, Jeff A" wrote:
> <SNIP>
>
> > Dynamic class loading (without fleshing out the error
> > handling) looks like this:
> >
> > String actionClassName = ...; // Whatever action class you need
> > Class actionClass = Class.forName(actionClassName);
> > Action action = (Action) actionClass.newInstance();
>
> How do I make this work with the HashTable/Map/Set so that I can ensure only
> a single instance of any action class? I assume I can load all the action
> classes into a HashSomething on the servlets init() and get the appropriate
> action and call perform()? Is this correct?
>
This is why I use *two* Hashtables, not one.
The first Hashtable -- lets call it "actions" -- is configured in the init()
method, based on parameters, or reading an XML file, or however you like. The key
is the request URI pattern to match against, and the value is the name of the Java
class to load for this Action.
The second Hashtable -- lets call it "instances" -- is dynamically built as
requests are processed in the doGet()/doPost() method. The key is again the
request URI pattern to match against, but the value is the Action instance itself.
This Hashtable starts out empty.
To see how this works, consider the following logic in the doGet()/doPost() method
of the controller servlet (you will need to add appropriate exception handling):
// Identify the part of the request URI we want to use for matching
String requestURI = request.getRequestURI();
String matchPart = ...; // Extract the part you want to match against
// Find an action class instance to do be called
Action instance = (Action) instances.get(matchPart);
if (instance == null) { // FIrst time for this action
String actionClassName = (String) actions.get(matchPart);
if (actionClassName == null) {
... deal with an invalid request URI ...
}
Class actionClass = Class.forName(actionClassName);
instance = (Action) actionClass.newInstance();
instances.put(matchPart, instance);
}
// Now call the action
instance.perform(this, request, response);
As you can see, the "instances" table is filled as requests are called for the
first time. After that, the existing instance is reused.
Alternatively, you could load up the instances table in the init() method, and
dispense with the actions table, but I try to defer work until I really need it.
Craig McClanahan
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
Some relevant FAQs on JSP/Servlets can be found at:
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.html
http://www.jguru.com/jguru/faq/faqpage.jsp?name=JSP
http://www.jguru.com/jguru/faq/faqpage.jsp?name=Servlets