http://localhost:8080/SSHLearning/tags/ssh_sort
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="com.ssh.tags" extends="struts-default" namespace="/tags"> <action name="ssh_*" class="com.ssh.actions.ExampleAction" method="{1}"> <result name="success">/WEB-INF/pages/tags/{1}.jsp</result> </action> </package> </struts>
ExampleAction
package com.ssh.actions; import java.util.ArrayList; import java.util.List; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.ssh.beans.Student; public class ExampleAction extends ActionSupport { List<Student> list; private int type;//接受sort.jsp传来的排序信息 再传入sort.jsp的排序器中 //排序 public String sort(){ System.out.println("ExampleAction.sort"); Student s; list=new ArrayList<Student>(); for (int i=99;i>90;i--) { list.add(new Student(99-i, "rain", "男", i)); } ActionContext.getContext().put("students", list); return SUCCESS; } public void setType(int type) { this.type = type; } public int getType() { return type; } }
sort.jsp
这里basePath一定要写(tags/ssh_sort?type=1的url必须以项目根目录为起点)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> </head> <body> <s:bean id="stuCompBean" name="com.ssh.util.StudentComparator"> <s:param name="type"> <s:property value="type" /> </s:param> </s:bean> <table> <tr> <td> 姓名 </td> <td> <a href="tags/ssh_sort?type=1"> 学号 </a> </td> <td> 性别 </td> <td> <a href="tags/ssh_sort?type=2">年龄</a> </td> </tr> <s:sort comparator="#stuCompBean" source="#students"> <s:iterator id="stu" status="stus"> <tr <s:if test="#stus.even">style="background: blue"</s:if>> <td> <s:property value="name" /> </td> <td> <s:property value="id" /> </td> <td> <s:property value="sex" /> </td> <td> <s:property value="age" /> </td> <td> count: <s:property value="#stus.count" /> index: <s:property value="#stus.index" /> </td> </tr> </s:iterator> </s:sort> </table> </body> </html>
StudentComparator
package com.ssh.util; import java.util.Comparator; import com.ssh.beans.Student; public class StudentComparator implements Comparator<Student> { private int type; public int compare(Student s1, Student s2) { System.out.println(type); if (type == 1) return s1.getAge() - s2.getAge(); else return s1.getId() - s2.getId(); } public void setType(int type) { this.type = type; } }