13 Feb 2016

Struts2 Wildcard (Dynamic) Method Selection with Example

Generally, if we have 3 methods in  action class then we have to configure 3 separate action nodes inside struts.xml.

Consider the following actions:

The above actions can be mapped with 3 separate action nodes as:
<action name="addPerson" class="com.j2eekart.action.UserAction" method="add">
   <result name="success">/Welcome.jsp</result>
   <result name="error">/Error.jsp</result>
</action>
<action name="editPerson" class="com.j2eekart.action.UserAction" method="edit">
   <result name="success">/Welcome.jsp</result>
   <result name="error">/Error.jsp</result>
</action>
<action name="deletePerson" class="com.j2eekart.action.UserAction" method="delete">
   <result name="success">/Welcome.jsp</result>
   <result name="error">/Error.jsp</result>
</action>
Now you can imagine just to perform 3 actions of a user we have 3 action mapping nodes, then how complex it will be to configure all actions of an application.

To reduce this complexity Struts2 Framework provides the feasibility of Wildcard Method Section technique which dynamically selects appropriate method to call at runtime. The wildcard method selection can be implemented by using wildcard character '*' in action name value and place holder '{1}' in method value.

The wildcard method selection for the above 3 actions will be as shown below:
<action name="*Person" class="com.j2eekart.action.UserAction" method="{1}">
   <result name="success">/Welcome.jsp</result>
   <result name="error">/Error.jsp</result>
</action>
In the above wildcard method configuration, wildcard *Person specifies that any action that ends with Person will be handled by this action and method attribute value i.e., the place holder {1} is replaced with the name whatever before the Person.

Thus, wildcard *Person handles all addPerson, editPerson and deletePerson actions and dynamically select and call to their respective add(), edit() and delete() method.

Related Posts

Action Mapping in Struts2 

Action Extension in Struts2 

Hide “action” extension in Struts2 





Popular Posts

Write to Us
Name
Email
Message