Monday, March 2, 2009

Using property tag in Struts 2

This blog post intends to answer the following questions :-
  1. What is the usage of the property tag in Struts 2?
  2. How can I display a default value if a property is not present on a jsp page?
  3. What does the property tag do in Struts 2?
The property tag in Struts 2 is highly useful when you need to display contents on the screen, especially those associated with the session or context objects. The struts 2 framework makes use of the OGNL and value stack, which makes accessing these scoped attributes easier than before, enabling you to completely eliminate the need of any scriplet code or expression in your pages. The property tag can access any object that is visible in the value stack. All that you need to do is to provide the name of the object to the 'value' attribute of the tag.

As an example assume that there is an attribute in the session scope called 'username'. Now, to print the value of this attribute, I need to do the following.

<s:property value="#session.username"/>

Consider another scenario, when you submitted a form with a textfield called 'location' and it calls an action. This action has a setter and a getter method for the location field. The action does some processing and results in a jsp page being displayed. Now, in order for you to display this 'location' field on your resulting jsp page, all that you need to type is : -

<s:property value="session"/>

This is because since the action was the last thing that was called in the calling chain, the instance of the action class was on the top of the stack and hence we did not have to write any code to specify the instance whose getLocation() method we were attempting to call.

Sometimes, it is useful to display sensible defaults on your jsp page when the property tag retrieves value that is null. i.e. the value is not on the stack. For example, you might want to display a message saying that a user needs to login if the username is not in the session. This can be done as follows.

Welcome !! <s:property value="#session.username" default="Login To Use Your Superpowers"/>

Happy Programming ;)

Signing Off
Ryan

No comments: