---
title: "jqGrid与Struts2的结合应用（七） —— 浅谈排序"
author: "luocb1980"
date: "2013-01-05T22:41:47Z"
tags: []
categories: ["Web前端"]
slug: "jqgrid-struts2"
draft: false
lastmod: "2013-01-05T22:41:47Z"
id: 1762961
url: "https://luocb1980.iteye.com/blog/1762961"
---

转至：http://blog.csdn.net/gengv/article/details/5732698

作者：[gengv](http://my.csdn.net/gengv)

 

终于讲到排序了，这一部分应该说还是比较好理解的。

jqGrid通过colModel选项中的sortable来控制是否可以以某列的值排序。sortable的默认值是true，当设为false时，即此列不能用于排序。

 

**\[javascript]** [view plain](http://blog.csdn.net/gengv/article/details/5732698 "view plain")[copy](http://blog.csdn.net/gengv/article/details/5732698 "copy")

01. $(function(){
02. $("#gridTable").jqGrid({
03. ...
04. colModel: [
05. {name:"id",index:"id",label:"编码",width:40},
06. {name:"lastName",index:"lastName",label:"姓",width:80},
07. {name:"firstName",index:"firstName",label:"名",width:80},
08. {name:"email",index:"email",label:"电子邮箱",width:160,sortable:false},
09. {name:"telNo",index:"telNo",label:"电话",width:120,sortable:false}
10. ],
11. ...
12. });
13. });

当点击sortable为true的列首时，jqGrid会向Server发送排序请求，例如：  
http://localhost:8085/Hare/jqGridTest/jqGrid05.action?search=false&nd=1279006749246&rows=15&page=3&sidx=firstName&sord=asc

注：其中sord和sidx参数名都是在jqGrid的prmNames选项中设定的（可参考本系列文章的第一篇）。而sidx参数的值即各列的colModel的index选项值。（在查询和排序时，发送的关于列的参数都是基于colModel的index属性的）

后面的事情就交给服务器端的Action来处理了，还拿我们的Contact联系人列表为例。

既然我们可能会分别使用不同的字段来排序，那么就必须为Contact提供不同的Comparator来简化比较操作。因此我写了一个针对Contact的Comparator的工厂类，用来根据不同的字段提供不同的Comparator。

ContactComparatorFactory的代码：

 

 

**\[java]** [view plain](http://blog.csdn.net/gengv/article/details/5732698 "view plain")[copy](http://blog.csdn.net/gengv/article/details/5732698 "copy")

001. package cn.gengv.struts2ex.jqGrid;
002. import java.text.Collator;
003. import java.util.Comparator;
004. import com.byzl.hare.model.Contact;
005. public class ContactComparatorFactory {
006. private static Collator collator\_Chinese = Collator.getInstance(java.util.Locale.CHINA);
007. private final static Comparator&lt;Contact&gt; idComparator = new IdComparator();
008. private final static Comparator&lt;Contact&gt; firstNameComparator = new FirstNameComparator();
009. private final static Comparator&lt;Contact&gt; lastNameComparator = new LastNameComparator();
010. private final static Comparator&lt;Contact&gt; fullNameComparator = new FullNameComparator();
011. private final static Comparator&lt;Contact&gt; idCardNoNoComparator = new IdCardNoComparator();
012. private final static Comparator&lt;Contact&gt; nationalityComparator = new NationalityComparator();
013. public static Comparator&lt;Contact&gt; getComparator(String compareType) {
014. if ("id".equalsIgnoreCase(compareType)) {
015. return idComparator;
016. } else if ("firstName".equalsIgnoreCase(compareType)) {
017. return firstNameComparator;
018. } else if ("lastName".equalsIgnoreCase(compareType)) {
019. return lastNameComparator;
020. } else if ("fullName".equalsIgnoreCase(compareType)) {
021. return fullNameComparator;
022. } else if ("idCardNoNo".equalsIgnoreCase(compareType)) {
023. return idCardNoNoComparator;
024. } else if ("nationality".equalsIgnoreCase(compareType)) {
025. return nationalityComparator;
026. } else {
027. return null;
028. }
029. }
030. public static class IdComparator implements Comparator&lt;Contact&gt; {
031. public int compare(Contact c1, Contact c2) {
032. if (c1 == null && c2 == null) {
033. return 0;
034. } else if (c1 == null && c2 != null) {
035. return -1;
036. } else if (c1 != null && c2 == null) {
037. return 1;
038. } else {
039. int id1 = c1.getId();
040. int id2 = c2.getId();
041. return id1 == id2 ? 0 : (id1 &lt; id2 ? -1 : 1);
042. }
043. }
044. }
045. public static class FirstNameComparator implements Comparator&lt;Contact&gt; {
046. public int compare(Contact c1, Contact c2) {
047. if (c1 == null && c2 == null) {
048. return 0;
049. } else if (c1 == null && c2 != null) {
050. return -1;
051. } else if (c1 != null && c2 == null) {
052. return 1;
053. } else {
054. String s1 = c1.getFirstName();
055. String s2 = c2.getFirstName();
056. if (s1 == null && s2 == null) {
057. return 0;
058. } else if (s1 == null && s2 != null) {
059. return -1;
060. } else if (s1 != null && s2 == null) {
061. return 1;
062. } else {
063. return collator\_Chinese.compare(s1, s2);
064. }
065. }
066. }
067. }
068. public static class LastNameComparator implements Comparator&lt;Contact&gt; {
069. public int compare(Contact c1, Contact c2) {
070. if (c1 == null && c2 == null) {
071. return 0;
072. } else if (c1 == null && c2 != null) {
073. return -1;
074. } else if (c1 != null && c2 == null) {
075. return 1;
076. } else {
077. String s1 = c1.getLastName();
078. String s2 = c2.getLastName();
079. if (s1 == null && s2 == null) {
080. return 0;
081. } else if (s1 == null && s2 != null) {
082. return -1;
083. } else if (s1 != null && s2 == null) {
084. return 1;
085. } else {
086. return collator\_Chinese.compare(s1, s2);
087. }
088. }
089. }
090. }
091. public static class FullNameComparator implements Comparator&lt;Contact&gt; {
092. public int compare(Contact c1, Contact c2) {
093. if (c1 == null && c2 == null) {
094. return 0;
095. } else if (c1 == null && c2 != null) {
096. return -1;
097. } else if (c1 != null && c2 == null) {
098. return 1;
099. } else {
100. String s1 = c1.getFullName();
101. String s2 = c2.getFullName();
102. if (s1 == null && s2 == null) {
103. return 0;
104. } else if (s1 == null && s2 != null) {
105. return -1;
106. } else if (s1 != null && s2 == null) {
107. return 1;
108. } else {
109. return collator\_Chinese.compare(s1, s2);
110. }
111. }
112. }
113. }
114. public static class IdCardNoComparator implements Comparator&lt;Contact&gt; {
115. public int compare(Contact c1, Contact c2) {
116. if (c1 == null && c2 == null) {
117. return 0;
118. } else if (c1 == null && c2 != null) {
119. return -1;
120. } else if (c1 != null && c2 == null) {
121. return 1;
122. } else {
123. String s1 = c1.getIdCardNo();
124. String s2 = c2.getIdCardNo();
125. if (s1 == null && s2 == null) {
126. return 0;
127. } else if (s1 == null && s2 != null) {
128. return -1;
129. } else if (s1 != null && s2 == null) {
130. return 1;
131. } else {
132. return s1.compareToIgnoreCase(s2);
133. }
134. }
135. }
136. }
137. public static class NationalityComparator implements Comparator&lt;Contact&gt; {
138. public int compare(Contact c1, Contact c2) {
139. if (c1 == null && c2 == null) {
140. return 0;
141. } else if (c1 == null && c2 != null) {
142. return -1;
143. } else if (c1 != null && c2 == null) {
144. return 1;
145. } else {
146. String s1 = c1.getNationality();
147. String s2 = c2.getNationality();
148. if (s1 == null && s2 == null) {
149. return 0;
150. } else if (s1 == null && s2 != null) {
151. return -1;
152. } else if (s1 != null && s2 == null) {
153. return 1;
154. } else {
155. return collator\_Chinese.compare(s1, s2);
156. }
157. }
158. }
159. }
160. }

 

 

然后再来看JqGridBaseAction，其中添加了一个抽象方法，用来将数据结果进行排序。

 

**\[java]** [view plain](http://blog.csdn.net/gengv/article/details/5732698 "view plain")[copy](http://blog.csdn.net/gengv/article/details/5732698 "copy")

01. package cn.gengv.struts2ex.jqGrid;
02. // import ...
03. @SuppressWarnings("serial")
04. public abstract class JqGridBaseAction&lt;T&gt; extends ActionSupport {
05. ...
06. // (1)添加排序方法
07. public abstract void sortResults(List&lt;T&gt; results, String field, String order);
08. public String refreshGridModel() {
09. try {
10. List&lt;Criterion&gt; criteria = Collections.emptyList();
11. if(search == true) {
12. criteria = new ArrayList&lt;Criterion&gt;();
13. if(filters != null && filters.length()&gt;0) {
14. criteria.addAll(this.generateSearchCriteriaFromFilters(filters));
15. }
16. Criterion criterion = this.generateSearchCriterion(searchField, searchString, searchOper);
17. if(criterion != null) {
18. criteria.add(criterion);
19. }
20. }
21. List&lt;T&gt; results = Collections.emptyList();
22. int from = rows * (page - 1);
23. int length = rows;
24. if(loadonce) {
25. from = 0;
26. length = 100;
27. }
28. if(!criteria.isEmpty()) {
29. record = this.getResultSize(criteria);
30. results = this.listResults(criteria, from, length);
31. } else {
32. record = this.getResultSize();
33. results = this.listResults(from, length);
34. }
35. // (2)将结果排序
36. if(sidx != null && sord != null) {
37. sortResults(results, sidx, sord);
38. }
39. this.setGridModel(results);
40. total = (int) Math.ceil((double) record / (double) rows);
41. return SUCCESS;
42. } catch (Exception e) {
43. e.printStackTrace();
44. this.addActionError(e.getMessage());
45. return ERROR;
46. }
47. }
48. ...
49. }

 

而在ListContactsAction中提供了方法实现：

 

**\[java]** [view plain](http://blog.csdn.net/gengv/article/details/5732698 "view plain")[copy](http://blog.csdn.net/gengv/article/details/5732698 "copy")

01. package cn.gengv.struts2ex.jqGrid;
02. import java.util.Collections;
03. import java.util.Comparator;
04. import java.util.List;
05. import com.byzl.hare.dao.impl.Criterion;
06. import com.byzl.hare.model.Contact;
07. import com.byzl.hare.service.ContactService;
08. @SuppressWarnings("serial")
09. public class ListContactsAction extends JqGridBaseAction&lt;Contact&gt; {
10. ...
11. @Override
12. public void sortResults(List&lt;Contact&gt; results, String field, String order) {
13. // (1)根据field获得对应的Comparator
14. Comparator&lt;Contact&gt; comparator = ContactComparatorFactory.getComparator(field);
15. if(comparator != null) {
16. // (2)使用Comparator排序
17. Collections.sort(results, comparator);
18. // (3)如果需要的排序顺序为desc，则颠倒顺序
19. if("desc".equals(order)) {
20. Collections.reverse(results);
21. }
22. }
23. }
24. ...
25. }

 

 

![](http://hi.csdn.net/attachment/201007/13/0_12790241728C3L.gif)

不过这个例子存在一定的局限性，即只能将当前页中的数据根据某列进行排序；而不能跨页间进行数据排序。之所以存在这种局限，也是源于实际应用中的客观限制。还以这个例子来说，数据库里总共模拟了两万多条数据记录。如果每次要将这些记录进行排里的话，除非有数据库索引支持，否则所要消耗的时间也是相当客观的，对于用户体验来说，几乎就是灾难。如果数据量更多的话，结果可想而知。

因此，我们应该换一个角度来看这个问题，用户之所以使用排序，更多的目的还是在于查找数据方便，既然我们可以提供条件查询（尤其是复杂条件查询），那么用户对于排序的需求也就不会那么迫切了。同时也可以体会到，排序更多地应用在少量数据的场合下。