File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Struts and the fly likes Can one action class have more than one Form class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Can one action class have more than one Form class" Watch "Can one action class have more than one Form class" New topic

Can one action class have more than one Form class

Dee Gee

Joined: May 10, 2006
Posts: 10

Is it possible to have one action class for more that one form class.
If yes, are there any constraints or any pitfalls we should take care of?

Thank You
Manoj Raghuwanshi
Ranch Hand

Joined: Jun 20, 2004
Posts: 75
Not possible
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
Actually, yes, this is possible. There is a one-to-one relationship between an Action Mapping (The <action> tag in struts-config.xml) and an ActionForm. However, Multiple Action Mappings can point to the same Action Class, thereby making the same Action class use multiple action forms.

Since the parameter passed into the execute() method is of type ActionForm, you can cast it to whatever subclass of ActionForm you're expecting.

I wouldn't call this best practice, though. Generally it's better to have one action class only deal with one ActionForm.

I can think of one scenario, though, where this would be a reasonable solution: Suppose you had a number of pages that are only slightly different, and the processing for those pages is much the same. You might have all the ActionForms for these pages subclass a base ActionForm that has all the common elements between them. You could also point the Action mappings for each to the same Action class. In the execute method, you could first cast the ActionForm parameter to the base ActionForm class and perform all the common processing, and then based on the action path (mapping.getPath) use if/else logic to cast to the correct subclass and do the remainder of the processing.

Consultant, Sima Solutions
I agree. Here's the link:
subject: Can one action class have more than one Form class
It's not a secret anymore!