Tuesday, March 3, 2009

Specifying Action Method In Struts 2

This post intends to answer the following questions : -
  1. How call multiple methods of the same action class as separate actions?
  2. How to configure different methods as action methods?
  3. Can we configure methods other than execute() to be called when we have call an action?
Struts 2 makes it possible to call any ppublic method in a class instead of the execute() method. This is possible by simple making a small configuration change in the struts.xml file for the required action.

By using this feature you can actually create a single action class and have many methods that perform different tasks. You can have as many different actions as there are methods in your class. You need not make any changes anywhere in your action class to enable it to service more than one type of action request. This is simply done by using the struts.xml file. However your functions must have the following syntax

public String fucntionName()
{
}

Consider an action class with the following two functions

MyActions.java
------Source Code Starts Here------
.
.
import .......
.
.
public class MyActions extends ActionSupport
{
.
.
.
public String method1()
{
//some code
//return SUCCESS/ERROR etc etc
}


public String method2()
{
//some code
//return SUCCESS/ERROR etc etc
}
------Source Code Ends Here------

Now, in order to call these methods on different action requests, the following configuration in struts.xml will suffice :-

struts.xml
------Source Code Starts Here------
.
.
.
<action name="action1" class="MyActions" method="method1">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
<result name="input">/error.jsp</result>
</action>
<action name="action2" class="user.My" method="method2">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
<result name="input">/error.jsp</result>
</action>

.
.
.
------Source Code Ends Here------

Notice the 'method' attribute that is used to specify the method that needs to be called for an action. All the rest of the code is the same as in regular action classes.

Happy Programming ;)

Signing Off
Ryan

2 comments:

Anonymous said...

thanks for the interesting information

Deepanshu gupta said...

in this example class name is different is it work properly?