Pages

Saturday, November 1, 2008

Filtering and Projecting with OGNL - struts 2

This is important OGNL feature when we are working with collections
to generate the UI components with Struts 2 tag libraries. To explain this, I will consider a class called "
Employee". Suppose we have a list of employee objects from the "ValueStack".

public class Employee{

private int age;

private String firstName;

private String lastName;

//......

}

Now, you want to filter out the employees where the age is grater than 30. The OGNL filtering will resolve the problem. You can get this as fallows .

<s:set name="empList" value="employeeList.{?#this.age > 30}"></s:set>
<s:iterator value="#empList">
<s:property value="firstName"/>
</s:iterator>

Here, #this refers to the "employeeList" which is resolved in "ValueStack". That is it, about filtering. Now I will explain, how we use the projection. Think, you want to have a separate list with employee's full name. The OGNL projection feature will lead us to achieve it .

<s:set name="empNameList"
value="employeeList.{firstName + ' ' + lastName}"></s:set>
<s:iterator value="#empNameList" status="stat">
<s:property value="#empNameList[#stat.getIndex()]"/>
</s:iterator>

1 comments:

Share

Widgets