Thursday, July 29, 2010

Struts2 - Adding Properties to the pageContext

In struts2, to access a property inside a JSP that we set in the overridden execute method of Action Interface, we use the following property tag:
<s:property value="results" />
where s is an alias for struts-tags tag library and results is a Collection (can be anything) that we've populated in execute method. Note here that it must be a variable/property in you action handler class with both of its getter and setter methods available. The property tag will call the getResults() getter method.
This is clean. But it should be noted that results is not available in the pageContext of the page being processed currently. So, for example, if you want to use the results collection inside a jsp scriptlet by doing something like
this will not work. You cannot even say something like
Anyways, it's possible and pretty clean too :) All you've to do is to set the pageContext attribute by using another struts tag,
<s:set name="pageResults" value="%{results}" />
This is equivalent to
but the later won't work. The name is what you want to name the results in the pageContext, like a variable name; and the value is its value. So here, Set tag will call getResults() and assign the returned value to a pageContext variable called pageResults.

That's it :)