Pages Navigation Menu

Coding is much easier than you think

Struts 2 Dynamic Method Invocation using Action Wildcards

 
This tutorial is a continuation of previous example ( DispatchAction functionality ). In this example you will see about avoiding configuration of separate action mapping for each method in Action class by using the wildcard method. Look at the following action mapping to under stand the concept.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Action mapping From previous example
 

<struts>

<package name="default" extends="struts-default">

	<action name="Number" class="com.simplecode.action.CalculatorAction">
		<result name="success">/curd.jsp</result>
	</action>
	<action name="addNumber" method="add"
		class="com.simplecode.action.CalculatorAction">
		<result name="success">/curd.jsp</result>
	</action>
	<action name="multiplytNumber" method="multiply"
		class="com.simplecode.action.CalculatorAction">
		<result name="success">/curd.jsp</result>
	</action>
	<action name="subtractNumber" method="subtract"
		class="com.simplecode.action.CalculatorAction">
		<result name="success">/curd.jsp</result>
	</action>
		<action name="divideNumber" method="divide"
		class="com.simplecode.action.CalculatorAction">
		<result name="success">/curd.jsp</result>
	</action>

</package>
</struts>

 
Action mapping Using Wildcard
 

<struts>
<package name="default" extends="struts-default">
    <action name="*Number" method="{1}" class="com.simplecode.action.CalculatorAction">
	<result name="success">/curd.jsp</result>
    </action>
</package>
</struts>

 
As you can see we have replaced all the method names with an asterisk(*) symbol. The word that matches for the first asterisk will be substituted for the method attribute. So when the request URL is “divideNumber” the divide() method in the CalculatorAction class will be invoked.
 
Do read :

 
Note :
 
1. We can also substitute asterisk in the jsp pages.
For example
 

    <action name="*Number" method="{1}">
	<result name="success">/{1}curd.jsp</result>
    </action>

 
2. The wild card can be placed in any position in a action name
For example
 

    <action name="Number*" method="{1}">
	<result name="success">/{1}curd.jsp</result>
    </action>

 
3. You can have multiple wild card , for example
 

    <action name="*Number*" method="{1}">
	<result name="success">/{1}curd{2}.jsp</result>
    </action>

 
To match first wildcard, we have to use {1}, to match second wild card we have to use {2}.
 


 
Hope you understand about Action Wildcards uses. Thanks for reading :)
 

About Mohaideen Jamil