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
pageContext.getAttribute("results")
this will not work. You cannot even say something like
request.getAttribute("results")
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
pageContext.setAttribute("pageResults",results)
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 :)

6 comments:

Liferay said...

This is a great blog,this website provides very useful tips.we are going to add it to out liferay consultant and Liferay information blog.http://www.mpowerglobal.com/web/guest/blog so our visitors can read your news,as you are a reputable source.Thanks Andrew Marks

Salman Jamali said...

Sure Andrew, thanks!

Anonymous said...

Excellent blog. Got clear answer

tania said...

nice blog good article ...

Anonymous said...

awesome....thanks for the tip...neatly explained..:-)

dressing styles said...

Hi..am trying same thing...till it is not working for me...any suggestion????