MyComparator.java
public class MyComparator implements Comparator<Object> {
public int compare(Object o1, Object o2) {
XmxxBean xmxxBean1 = (XmxxBean)o1 ;
XmxxBean xmxxBean2 = (XmxxBean)o2 ;
//没啥用
// xmxxBean1 = (XmxxBean)o2;
// xmxxBean2 = (XmxxBean)o1;
//按id进行排序
// return xmxxBean1.getXMXXID() - (xmxxBean2.getXMXXID());
//按名称进行排序
return xmxxBean2.getXMMC().compareToIgnoreCase(xmxxBean1.getXMMC());
}
}
SortTagAction.java
public class SortTagAction extends ActionSupport {
@Override
public String execute() throws Exception {
List<XmxxBean> list_value = new ArrayList<XmxxBean>();
list_value.add(new XmxxBean(1,"XMXXBH002","OA"));
list_value.add(new XmxxBean(3,"XMXXBH001","ERP"));
list_value.add(new XmxxBean(2,"XMXXBH005","EXAM"));
list_value.add(new XmxxBean(5,"XMXXBH004","ZC"));
list_value.add(new XmxxBean(4,"XMXXBH003","HM"));
HttpServletRequest request = ServletActionContext.getRequest();
// for(int i = 0 ; i<list_value.size() ; i++){
// System.out.println(list_value.get(i).getXMXXID());
request.setAttribute("list_values", list_value);
// }
return "sortTag";
}
}
struts.xml
<action name="sortTag" class="com.butone.struts2.taguser.SortTagAction">
<result name="sortTag">/taguser/sortTag.jsp</result>
</action>
sortTag.jsp
<s:form>
<s:bean id="mycomparator" name="com.butone.struts2.taguser.MyComparator" />
<table border="1" width="200">
<s:sort source="#request.list_values"
comparator="#mycomparator" >
<s:iterator status="st" >
<!-- even索引是否为偶数
odd索引是否为奇数
count返回当前迭代了几个元素
index返回当前元素的索引
first当前是否是第一个元素
last当前是否是最后一个元素
-->
<tr <s:if test="#st.even">style="background-color:#bbbbbb"</s:if>>
<td>
<A href="#"><s:property value="XMMC"/></A>
</td>
</tr>
</s:iterator>
</s:sort>
</table>
</s:form>
http://localhost:8080/struts2/sortTag.action