Search from Struts2 Library

Sunday, September 21, 2008

Push tag

Whereas the set tag allows you to create new references to values, the push tag allows you to push properties onto the ValueStack. This is useful when you want to do a lot of work revolving around a single object. With the object on the top of the ValueStack, its properties become accessible with first-level OGNL expressions. Any time you access properties of an object more than a time or two, it’ll probably save a lot of work if you push that object onto the stack. Table 6.4 provides the attribute for the push tag.



Here’s an example of the usage:
<s:push value="user">
This is the "<s:property value="portfolioName"/>" portfolio,
created by none other than <s:property value="username"/>
</s:push>

This push tag pushes a property named user, which is exposed by the TagDemo action as a JavaBeans property, onto the top of the ValueStack. With the user on top of the stack, we can access its properties as top-level properties of the ValueStack virtual object, thus making the OGNL much simpler. As you can see, the push tag has a start tag and close tag. Inside the body of the tag, we reference the properties of the user object as top-level properties on the ValueStack. The closing tag removes the user from the top of the ValueStack.

Important :
The push tag, and even the set tag to a limited extent, can be powerful when trying to reuse view-layer markup. Imagine you have a JSP template that you’d like to reuse across several JSP result pages. Consider the namespace of the OGNL references in that JSP template. For instance, maybe the template’s tags use OGNL references that assume the existence of a User object exposed as a model object, as in ModelDriven actions. In this case, the template’s tags would omit the user property and refer directly to properties of the user, for example <s:property value="username"/>.
If you try to include this template in the rendering of a result whose action exposes a User object as a JavaBeans property, rather than a model object, then this reference would be invalid. It would need to be
<s: value="user.username"/>.
Luckily, the push tag gives us the ability to push the user object itself to the top of the ValueStack, thus making the top-level references of the template valid in the current action. In general,the push tag and the set tag can be used in this fashion.

No comments: