SubClassing in Struts

This tutorial discusses about the need of  subclassing in Struts Action class.

Have you ever been in trouble decribing tons of action classes to do  jobs which are related having same data to handle(a single formBean).And here is your answer.

Consider a usual scenario

AddEditDelete User

Add Edit Delete User

Here you know that one action class can refer to only one formBean and you are using three action classes to define three functions add user,delete user,edit user which uses the same formBean

Now consider a restructuring in this way which you actually need

Here You are using Action subclassing to achieve this format.

Now the changes in the action class.

1.Instead of extending action i am extending DispatchAction here.

And so there will be no execute method ,instead we can specify our own method name but the signature should be intact as that of an execute function

public ActionForward addUser(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception { }

public ActionForward deleteUser(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception { }

public ActionForward editUser(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception { }

These three functions do the specified jobs ,implied by their names.

For doing this subclassing you need to edit the struts-config file so that it can recognise which function to take based on the submit from a jsp page.

Inorder to do that we specify parameter attribute in our action class definition in the struts-config.

<action name=”formBean” path=”/path” scope=”session” type=”dojeg.actions.Action” parameter=”func”>

here my parameter value is func,now you are ready to do the subclassing.

But how to do it.

The Add User is called when the url is like

/path.do?func=addUser

The Edit User is called when the url is like

/path.do?func=editUser

The Delete  User is called when the url is like

/path.do?func=deleteUser

Hope you have understood this method

Now how to access these from  jsp page.

Simple: <html:submit  property=”func” value=”addUser”></html:submit>

and form  tag as:html:form action=”/path”> where path is my action class name

Here when user clicks the Submit button addUser function is evoked

Thats the way to do it.
We can use LookUpDispatchAction,MappingDispatchAction(Struts 1.2) to do the same.

LookupDispacthAction helps to specify the names separate from being hardcoded into jsp page.

Leave a Reply