Archive for the ‘Struts2 Tag Reference’ Category

Struts2 Control Tags - Using iterator Tag

Wednesday, January 23rd, 2008

Download Source | View Demo

iterator tag can be used to loop over a collection of objects. The only requirement is that the collection should be of type java.util.Collection or java.util.iterator.

Here is a sample use,

Inside the iterator, the top of the value stack is the current object in the loop. Hence when you access “name”, it is actually “current_list_object.name”.

The current object is pushed to the value stack using the “id” field as the key. Hence referring “#userobj.name” is same as “name”. Similarly status field value (in this case user_stat) is the key in which the iterator status object is pushed. Hence you can check for an even row using the expression #user_stat.even which returns a boolean value.

Check out the following sample which demonstrates the use of iterator tag. In this IterateDemo action class populates dummy customer data is a list and passes it to iteratedemo.jsp. Using Struts2 iterator, the customer listing is printed out. Note the use of iterator status for alternate coloring of the rows. This sample also shows the use of stylesheets.

IterateDemo.java

Customer.java

iteratedemo.jsp

struts.xml

Parameters for iterator tag

Name Required Default Evaluated Type Description
id false false String Value stack key in which the current object is pushed
value false false String The list being iterated
status false false false String Value stack key in which the iterator status is stored

Struts2 Control Tags – Using if Tag

Tuesday, January 22nd, 2008

Struts2 if tag can be used for basic conditional flow. Using OGNL syntax, all types of conditional checks are possible. This tag can be followed with elseif and else blocks. Given below are some examples of if tag usage.

Sample application demonstrating usage of Struts2 if tag
This sample contains a single page with a link. Whenever user clicks on the link, the clicked link name is shown below.

When a link is clicked, its id is copied to the linkid hidden field using JavaScript and IfDemo action is invoked. Struts2 automatically maps this hidden field to linkid field in IfDemo action class. Then it renders the ifdemo.jsp. At this point, class variables in IfDemo action class are automatically available in ifdemo.jsp (since they are pushed to value stack). The if tag in JSP checks for the value of linkid in value stack and prints it out.

Action Class - IfDemo.java

Struts configuration - struts.xml

Sample screen - ifdemo.jsp

Parameters for if tag

Name Required Default Evaluated Type Description
test true false boolean content inside the tag is displayed only if this boolean expression is true