[Webwork-devel] Sorting facilities expanded + example
Brought to you by:
baldree,
rickardoberg
From: Rickard <ri...@xp...> - 2001-11-15 11:34:44
|
Hey I just put together a very simple example of a log4j console, which simply outputs the categories and the log levels that have been enabled for each category. While doing so I had the need to use the "sort" tag to sort the list of categories according to their name. With the current CVS code I would have had to write a bean that provides a comparator that would do this sorting. While that would have worked, I wanted a more generic approach that one could use without having to do custom coding. So, what I did was to extend the Sorter JavaBean to include a method getComparator(String anExpression) which creates a comparator that can compare two values that will be obtained by using the given WebWork expression on them. For example, if I have a list of Person objects, and want to output them sorted by name (Person.getName()), then I simply have to call Sorter.getComparator("name") to get a comparator that can be used for the sort operation. Thus, the category listing JSP code becomes (table header/footer removed): <webwork:bean name="'webwork.util.Sorter'" id="sorter"/> <webwork:action name="'log4j.categories'"> <form action="log4j.update.action" method="post"> <iterator:sort source="categories" comparator="@sorter/comparator('name')"> <webwork:iterator> <tr> <td><webwork:property value="name"/></td> <td><input type=checkbox name="<webwork:property value="name"/>/debug" value="true" <webwork:if test="debugEnabled==true">checked</webwork:if>></td> <td><input type=checkbox name="<webwork:property value="name"/>/info" value="true" <webwork:if test="infoEnabled==true">checked</webwork:if>></td> </tr> </webwork:iterator> </iterator:sort> </form> </webwork:action> -- The log4j.categories action simply provides the list of categories, and according to the JavaDoc the Category class has a getName() method, hence the "@sorter/comparator('name')" attribute in the sort tag. The expression can be any WW expression, but I think most cases will be of this rather simple variant. Nice! :-) Any thoughts on this? There is also a method in the Sorter to get the reverse comparator. I'm considering adding a boolean flag to the method for forward/backward ordering selection, which will allow dynamic selection of order. /Rickard ps. The above is not yet commited to CVS. Watch the dev list. -- Rickard Öberg |