Struts2 sort標籤
阿新 • • 發佈:2018-12-11
傳統的頁面例如購書系統,都會有根據作者的名稱或者價格進行排序,在以前的解決方法中,都依賴的是底層的sql語句來解決的;
現在我們在web資源裡面就可以自己解決了,減少了不少的sql底層程式碼和servlet程式碼;
下面我們就開始學習一下這個知識點把!
第一步,就是一個Action類,裡面有屬性有方法
package cn.com.action; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.struts2.interceptor.RequestAware; public class Person implements RequestAware{ private String name; private Integer age; private List<Person> list=new ArrayList<Person>(); public List<Person> getList() { return list; } public void setList(List<Person> list) { this.list = list; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Person(String name, Integer age) { super(); this.name = name; this.age = age; } public Person(){} public String execute(){ list.add(new Person("EQ",14)); list.add(new Person("QQ",11)); list.add(new Person("CQ",15)); list.add(new Person("SS",13)); list.add(new Person("WW",12)); PersonCompare com=new PersonCompare(); requetmap.put("com", com); return "success"; } private Map<String, Object> requetmap; @Override public void setRequest(Map<String, Object> arg0) { requetmap=arg0; } }
第二步 就是一個介面類,繼承Comparator<T>介面
package cn.com.action; import java.util.Comparator; public class PersonCompare implements Comparator<Person>{ /* * author:命運的信徒 * date:2018/12/11 * arm:sort標籤的排序 */ @Override public int compare(Person o1, Person o2) { // TODO Auto-generated method stub return o1.getAge().compareTo(o2.getAge()); } }
第三步 web資源的排序
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% 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%>"> <title>sort標籤排序</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <!-- comparator="排序的方式" soure="集合名稱" var="屬性的名稱" 代表的就是Comparator<Person>裡面的屬性--> <s:sort comparator="#request.com" source="list" var="pp"> <!-- value="#attr.person" 迴圈遍歷的物件--> <s:iterator value="#attr.pp" > ${name }-- ${age }<br> </s:iterator> </s:sort> </body> </html>
struts.xml
<action name="gg" class="cn.com.action.Person" method="execute">
<!-- result="名稱" 當名稱是error的時候,代表著對應的是<result name="error"></result>這個資訊;exception="異常全類名"-->
<!-- <exception-mapping result="error" exception="java.lang.ArithmeticException">
</exception-mapping>
<result name="error">/context.jsp</result> -->
<result name="success">/sort.jsp</result>
</action>