Search from Struts2 Library

Monday, September 22, 2008

Action tag

This tag allows us to invoke another action from our view layer. Use cases for this might not be obvious at first, but you’ll probably find yourself wanting to invoke secondary actions from the result at some point. Such scenarios might range from integrating existing action components to wisely refactoring some action logic. The practical application of the action tag is simple: you specify another action that should be invoked. Some of the most important attributes of this tag include the executeResult attribute, which allows you to indicate whether the result for the secondary
action should be written into the currently rendering page, and the name and namespace attributes, by which you identify the secondary action that should fire. By default, the namespace of the current action is used. Table below contains the details of the important attributes.

Here’s an example that chooses to include the secondary action’s result:

<h3>Action Tag</h3> <h4>This line is from the ActionTag action's result.</h4> <s:action name="TargetAction" executeResult="true"/>

Note that the default is to not include the result, so we have to change this by setting the executeResult attribute to true. The output looks like figure below.
One thing to note is that the result of the secondary action should probably be an HTML fragment if you want it to fit into the primary page.
Often, you might want the secondary action to fire, but not write a result. One
common scenario is that the secondary action, instead of writing to the page, will produce side effects by stashing domain data somewhere in the ActionContext. After control returns, the primary action can access that data. The following markup shows how to target an action in this fashion:

<h4>This line is before the ActionTag invokes the secondary action.</h4> <s:action name="TargetAction"/> <h4>Secondary action has fired now.</h4> <h5>Request attribute set by secondary action = </h5> <pre> <s:property value="#request.dataFromSecondAction"/></pre>

The execution of the secondary action is a bit of a side effect unless we reach back to get something that it produced. We retrieve a property that was set by the secondary action into the request map, just to prove that the secondary action fired. You can check the output yourself by visiting the chapter 6 sample code. Many times, however, a side effect may be just what you want. Note also that the secondary action can receive, or not receive, the request parameters from the primary request, according to the ignoreContextParams attribute.
That finishes up our coverage of data tags. In the next section, we’ll show how to introduce conditional logic to your page rendering with the control tags.

No comments: