1. 程式人生 > >Telerik Kendo UI 那點事【3】GridView MVVM前後臺聯動服務端分頁、分組、過濾(查詢)、排序

Telerik Kendo UI 那點事【3】GridView MVVM前後臺聯動服務端分頁、分組、過濾(查詢)、排序

中文化之後,我們開始具體使用kendo ui元件。經常開發系統的我,通常從最常用的控制元件用起,那就是表格控制元件GridView!現在的軟體系統基本上就是標籤框、文字框、選擇框、樹、表格堆砌而成。因此接觸任何一種UI元件的時候,我通常都最為關注GridView,表格控制元件。小小的表格控制元件,做的好,能夠給前端呈現和使用帶來很好的感受的同時,還能夠大幅度降低開發的工作量。

Kendo UI在這方面讓我十分滿意,甚至是震驚。因為它的GridView不僅僅是能夠簡單的在呈現層進行資料的過濾、排序、分組,關鍵是還能通過簡單的配置,讓介面的過濾、排序、分組與後臺直接聯動。相當於只要是呈現的資料列,如果要查詢,根本不必再在表格的上方做一堆標籤選擇區。當然這也是對軟體開發模型的一大挑戰,習慣了通過標籤框、選擇框等一堆控制元件指定條件,生成where條件,然後在點查詢的時候,進行後臺查詢再呈現的開發方式,已經完全過時,不僅不夠高效,而且開發起來浪費大量時間,使用者使用時,也並不直觀,對於條件對查詢後果的影響,使用者根本不清楚,有時因為設定大量查詢條件,而導致沒有查詢結果時,還很惱火。

二、直接聯動,無sql,無拼裝,查詢呈現。

kendo ui 的GridView控制元件,通過MVVM繫結資料來源,通過REST-Full風格的URL來與spring mvc的後臺進行通訊,就使用簡單的GridView,就能直接實現對後臺資料的實時查詢、修改、增加、刪除。並且無需寫什麼sql或者hql,也不需要拼裝什麼nosql的條件。一切都是完美聯動。介面的操作會生成條件物件,整個框架體系渾然一體,後端hibernate通過對前端物件反饋的條件資料進行自動拼裝,查詢得到結果。

說了這麼多,很多人看的可能覺得頭暈,不如程式碼來的爽。那麼就讓我們領教一下kendo UI的GridView之美吧!

頁面的頭部就忽略了,需要head的到前一篇文章看一下吧。body的部分,如下寫,就可以使用GridView。

頭部首先要增加REST-Full風格的CURD連線定義(個人習慣,便於工程管理,你也可以直接寫到js裡)

<c:url value="/kendo/test6.json" var="transportReadUrl" />
<c:url value="/kendo/test6c.json" var="transportCreateUrl" />
<c:url value="/kendo/test6u.json" var="transportUpdateUrl" />
<c:url value="/kendo/test6d.json" var="transportDestroyUrl" />

然後是body部分:

	<div>
				<div id="grid" style="height:580px"></div>
	</div>
	
	<script>
		$(document).ready(function() {
			$("#grid").kendoGrid({
				"columnMenu" : true,
				"dataSource" : {
					"schema" : {
						"total" : "total",
						"model" : {
							"id" : "objectId",
							"fields" : {
								"objectId" : {
									"type" : "number"
								},
								"age" : {
									"type" : "number"
								},
								"name" : {
									"type" : "string"
								},
								"bdate" : {
									"type" : "date"
								}
							}
						},
						"data" : "data",
						"groups" : "data"
					},
					"serverFiltering" : true,
					"transport" : {
						"destroy" : {
							"dataType" : "json",
							"contentType" : "application/json",
							"type" : "POST",
							"url" : "${transportDestroyUrl}"
						},
						"update" : {
							"dataType" : "json",
							"contentType" : "application/json",
							"type" : "POST",
							"url" : "${transportUpdateUrl}"
						},
						"read" : {
							"dataType" : "json",
							"contentType" : "application/json",
							"type" : "POST",
							"url" : "${transportReadUrl}"
						},
						"create" : {
							"dataType" : "json",
							"contentType" : "application/json",
							"type" : "POST",
							"url" : "${transportCreateUrl}"
						},
						"parameterMap" : function(options) {
							return JSON.stringify(options);
						}
					},
					"batch" : false,
					"serverSorting" : true,
					"pageSize" : 10.0,
					"serverPaging" : true,
					"serverGrouping" : true
				},
				"toolbar" : [ {
					"text" : "新增記錄",
					"name" : "create"
				} ],
				"reorderable" : true,
				"filterable" : true,
				"pageable" : {
					"input" : true,
					"buttonCount" : 5.0,
					"pageSize" : 10.0,
					"pageSizes" : [ 5, 10, 15, 20, 30 ],
					"refresh" : true
				},
				"sortable" : true,
				"columns" : [ {
					"field" : "objectId",
					"title" : "編號",
					"hidden" : true
				}, {
					"field" : "name",
					"title" : "姓名"
				}, {
					"field" : "age",
					"title" : "年齡"
				}, {
					"field" : "bdate",
					"title" : "出生日期",
					"filterable" : {
						"ui" : "datetimepicker"
					},
					"format" : "{0:yyyy-MM-dd HH:mm:ss}"
				}, {
					"title" : " ",
					"command" : [ {
						"text" : "編輯",
						"name" : "edit"
					}, {
						"text" : "刪除",
						"name" : "destroy"
					} ]
				} ],
				"groupable" : true,
				"editable" : {
					"mode" : "inline"
				}
			});
		});
	</script>

接下來,後臺spring MVC控制層如下:

@Controller
public class KendoControl {

	@Autowired
	private SessionFactory sessionFactory;



	@RequestMapping(value = "/kendo/test6d", method = RequestMethod.POST)
	public TestObject delete(@RequestBody TestObject model) {
		System.out.println("delete Object-->" + model);
		sessionFactory.getCurrentSession().delete(model);
		return model;
	}

	@RequestMapping(value = "/kendo/test6u", method = RequestMethod.POST)
	public TestObject update(@RequestBody TestObject model) {
		System.out.println("update mapObject-->" + model);
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(model);
		session.flush();
		return model;
	}

	@RequestMapping(value = "/kendo/test6c", method = RequestMethod.POST)
	public TestObject create(@RequestBody TestObject model) {
		System.out.println("create mapObject-->" + model);
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(model);
		session.flush();
		return model;
	}

	@RequestMapping(value = "/kendo/test6", method = RequestMethod.POST)
	public DataSourceResult kendoTest6(
			@RequestBody com.kendoui.spring.models.DataSourceRequest request) {
		System.out.println("RequestBody-->" + request.toString());
		return request.toDataSourceResult(sessionFactory.getCurrentSession(),
				TestObject.class);
	}

}
各位肯定發現了,裡面有個DataSourceRequest類,還有個DataSourceResult類,所有的查詢都和Request相關,核心的實現已經形成了模式,並且通過模型完成了介面查詢與後端查詢的對映,因此介面選擇過濾、分組、排序等等操作時,read url會被呼叫,引數會被傳到spring的mvc控制層,並且反序列化為DataSourceRequest物件,物件即實現了所有的操作,不需要我們再去拼裝什麼sql!偉大而美麗吧!這兩個類是從kendo ui for JSP的DEMO工程中直接cp過來使用的,其中由於日期格式化的問題,修改了DataSourceRequest類。下面給出他們的原始碼!

實體類TestObject:

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


/**
 * TestObject entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name="test_object")
public class TestObject  implements java.io.Serializable {


    // Fields    

     private Long objectId;
     private String name;
     private Integer age;
     private Date bdate;


    // Constructors



	/** default constructor */
    public TestObject() {
    }

	/** minimal constructor */
    public TestObject(Long id) {
        this.objectId = id;
    }
    
    /** full constructor */
    public TestObject(Long id, String name, Integer age) {
        this.objectId = id;
        this.name = name;
        this.age = age;
    }

   
    // Property accessors
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")

    public Long getObjectId() {
        return this.objectId;
    }
    
    public void setObjectId(Long id) {
        this.objectId = id;
    }
    
    @Column(name="name")

    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    @Column(name="age")

    public Integer getAge() {
        return this.age;
    }
    
    public void setAge(Integer age) {
        this.age = age;
    }
    
	@Temporal(TemporalType.TIMESTAMP)
    @Column(name="bdate", length = 11)
    
    public Date getBdate() {
		return bdate;
	}

	public void setBdate(Date bdate) {
		this.bdate = bdate;
	}

	@Override
	public String toString() {
		return "TestObject [objectId=" + objectId + ", name=" + name + ", age="
				+ age + ", bdate=" + bdate + "]";
	}







}

DataSourceRequest:

package com.kendoui.spring.models;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.annotate.JsonAnySetter;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.transform.ResultTransformer;

public class DataSourceRequest {
	private int page;
	private int pageSize;
	private int take;
	private int skip;
	private List<SortDescriptor> sort;
	private List<GroupDescriptor> group;
	private List<AggregateDescriptor> aggregate;
	private HashMap<String, Object> data;

	private FilterDescriptor filter;

	public DataSourceRequest() {
		filter = new FilterDescriptor();
		data = new HashMap<String, Object>();
	}

	public HashMap<String, Object> getData() {
		return data;
	}

	@JsonAnySetter
	public void handleUnknown(String key, Object value) {
		data.put(key, value);
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTake() {
		return take;
	}

	public void setTake(int take) {
		this.take = take;
	}

	public int getSkip() {
		return skip;
	}

	public void setSkip(int skip) {
		this.skip = skip;
	}

	public List<SortDescriptor> getSort() {
		return sort;
	}

	public void setSort(List<SortDescriptor> sort) {
		this.sort = sort;
	}

	public FilterDescriptor getFilter() {
		return filter;
	}

	public void setFilter(FilterDescriptor filter) {
		this.filter = filter;
	}

	private static void restrict(Junction junction, FilterDescriptor filter,
			Class<?> clazz) {
		String operator = filter.getOperator();
		String field = filter.getField();
		Object value = filter.getValue();
		boolean ignoreCase = filter.isIgnoreCase();

		try {
			Class<?> type = new PropertyDescriptor(field, clazz)
					.getPropertyType();
			if (type == double.class || type == Double.class) {
				value = Double.parseDouble(value.toString());
			} else if (type == float.class || type == Float.class) {
				value = Float.parseFloat(value.toString());
			} else if (type == long.class || type == Long.class) {
				value = Long.parseLong(value.toString());
			} else if (type == int.class || type == Integer.class) {
				value = Integer.parseInt(value.toString());
			} else if (type == short.class || type == Short.class) {
				value = Short.parseShort(value.toString());
			} else if (type == boolean.class || type == Boolean.class) {
				value = Boolean.parseBoolean(value.toString());
			} else if (type == Date.class) {
				SimpleDateFormat df = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");

				String input = value.toString();
				value = df.parse(input);
			}
		} catch (IntrospectionException e) {
		} catch (NumberFormatException nfe) {
		} catch (ParseException e) {
		}

		switch (operator) {
		case "eq":
			if (value instanceof String) {
				junction.add(Restrictions.ilike(field, value.toString(),
						MatchMode.EXACT));
			} else {
				junction.add(Restrictions.eq(field, value));
			}
			break;
		case "neq":
			if (value instanceof String) {
				junction.add(Restrictions.not(Restrictions.ilike(field,
						value.toString(), MatchMode.EXACT)));
			} else {
				junction.add(Restrictions.ne(field, value));
			}
			break;
		case "gt":
			junction.add(Restrictions.gt(field, value));
			break;
		case "gte":
			junction.add(Restrictions.ge(field, value));
			break;
		case "lt":
			junction.add(Restrictions.lt(field, value));
			break;
		case "lte":
			junction.add(Restrictions.le(field, value));
			break;
		case "startswith":
			junction.add(getLikeExpression(field, value.toString(),
					MatchMode.START, ignoreCase));
			break;
		case "endswith":
			junction.add(getLikeExpression(field, value.toString(),
					MatchMode.END, ignoreCase));
			break;
		case "contains":
			junction.add(getLikeExpression(field, value.toString(),
					MatchMode.ANYWHERE, ignoreCase));
			break;
		case "doesnotcontain":
			junction.add(Restrictions.not(Restrictions.ilike(field,
					value.toString(), MatchMode.ANYWHERE)));
			break;
		}

	}

	private static Criterion getLikeExpression(String field, String value,
			MatchMode mode, boolean ignoreCase) {
		SimpleExpression expression = Restrictions.like(field, value, mode);

		if (ignoreCase == true) {
			expression = expression.ignoreCase();
		}

		return expression;
	}

	private static void filter(Criteria criteria, FilterDescriptor filter,
			Class<?> clazz) {
		if (filter != null) {
			List<FilterDescriptor> filters = filter.filters;

			if (!filters.isEmpty()) {
				Junction junction = Restrictions.conjunction();

				if (!filter.getFilters().isEmpty()
						&& filter.getLogic().toString().equals("or")) {
					junction = Restrictions.disjunction();
				}

				for (FilterDescriptor entry : filters) {
					if (!entry.getFilters().isEmpty()) {
						filter(criteria, entry, clazz);
					} else {
						restrict(junction, entry, clazz);
					}
				}

				criteria.add(junction);
			}
		}
	}

	private static void sort(Criteria criteria, List<SortDescriptor> sort) {
		if (sort != null && !sort.isEmpty()) {
			for (SortDescriptor entry : sort) {
				String field = entry.getField();
				String dir = entry.getDir();

				if (dir.equals("asc")) {
					criteria.addOrder(Order.asc(field));
				} else if (dir.equals("desc")) {
					criteria.addOrder(Order.desc(field));
				}
			}
		}
	}

	private List<?> groupBy(List<?> items, List<GroupDescriptor> group,
			Class<?> clazz, final Session session,
			List<SimpleExpression> parentRestrictions)
			throws IntrospectionException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		ArrayList<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

		if (!items.isEmpty() && group != null && !group.isEmpty()) {
			List<List<SimpleExpression>> restrictions = new ArrayList<List<SimpleExpression>>();

			GroupDescriptor descriptor = group.get(0);
			List<AggregateDescriptor> aggregates = descriptor.getAggregates();

			final String field = descriptor.getField();

			Method accessor = new PropertyDescriptor(field, clazz)
					.getReadMethod();

			Object groupValue = accessor.invoke(items.get(0));

			List<Object> groupItems = createGroupItem(group.size() > 1, clazz,
					session, result, aggregates, field, groupValue,
					parentRestrictions);

			List<SimpleExpression> groupRestriction = new ArrayList<SimpleExpression>(
					parentRestrictions);
			groupRestriction.add(Restrictions.eq(field, groupValue));
			restrictions.add(groupRestriction);

			for (Object item : items) {
				Object currentValue = accessor.invoke(item);

				if (!groupValue.equals(currentValue)) {
					groupValue = currentValue;
					groupItems = createGroupItem(group.size() > 1, clazz,
							session, result, aggregates, field, groupValue,
							parentRestrictions);

					groupRestriction = new ArrayList<SimpleExpression>(
							parentRestrictions);
					groupRestriction.add(Restrictions.eq(field, groupValue));
					restrictions.add(groupRestriction);
				}
				groupItems.add(item);
			}

			if (group.size() > 1) {
				Integer counter = 0;
				for (Map<String, Object> g : result) {
					g.put("items",
							groupBy((List<?>) g.get("items"),
									group.subList(1, group.size()), clazz,
									session, restrictions.get(counter++)));
				}
			}
		}

		return result;
	}

	private List<Object> createGroupItem(Boolean hasSubgroups, Class<?> clazz,
			final Session session, ArrayList<Map<String, Object>> result,
			List<AggregateDescriptor> aggregates, final String field,
			Object groupValue, List<SimpleExpression> aggregateRestrictions) {

		Map<String, Object> groupItem = new HashMap<String, Object>();
		List<Object> groupItems = new ArrayList<Object>();

		result.add(groupItem);

		if (groupValue instanceof Date) { // format date
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String formattedDate = formatter.format(((Date) groupValue)
					.getTime());
			groupItem.put("value", formattedDate);
		} else {
			groupItem.put("value", groupValue);
		}

		groupItem.put("field", field);
		groupItem.put("hasSubgroups", hasSubgroups);

		if (aggregates != null && !aggregates.isEmpty()) {
			Criteria criteria = session.createCriteria(clazz);

			filter(criteria, getFilter(), clazz); // filter the set by the
													// selected criteria

			SimpleExpression currentRestriction = Restrictions.eq(field,
					groupValue);

			if (aggregateRestrictions != null
					&& !aggregateRestrictions.isEmpty()) {
				for (SimpleExpression simpleExpression : aggregateRestrictions) {
					criteria.add(simpleExpression);
				}
			}
			criteria.add(currentRestriction);

			groupItem.put("aggregates",
					calculateAggregates(criteria, aggregates));
		} else {
			groupItem.put("aggregates", new HashMap<String, Object>());
		}
		groupItem.put("items", groupItems);
		return groupItems;
	}

	@SuppressWarnings({ "serial", "unchecked" })
	private static Map<String, Object> calculateAggregates(Criteria criteria,
			List<AggregateDescriptor> aggregates) {
		return (Map<String, Object>) criteria
				.setProjection(createAggregatesProjection(aggregates))
				.setResultTransformer(new ResultTransformer() {
					@Override
					public Object transformTuple(Object[] value,
							String[] aliases) {
						Map<String, Object> result = new HashMap<String, Object>();

						for (int i = 0; i < aliases.length; i++) {
							String alias = aliases[i];
							Map<String, Object> aggregate;

							String name = alias.split("_")[0];
							if (result.containsKey(name)) {
								((Map<String, Object>) result.get(name)).put(
										alias.split("_")[1], value[i]);
							} else {
								aggregate = new HashMap<String, Object>();
								aggregate.put(alias.split("_")[1], value[i]);
								result.put(name, aggregate);
							}
						}

						return result;
					}

					@SuppressWarnings("rawtypes")
					@Override
					public List transformList(List collection) {
						return collection;
					}
				}).list().get(0);
	}

	private static ProjectionList createAggregatesProjection(
			List<AggregateDescriptor> aggregates) {
		ProjectionList projections = Projections.projectionList();
		for (AggregateDescriptor aggregate : aggregates) {
			String alias = aggregate.getField() + "_"
					+ aggregate.getAggregate();
			if (aggregate.getAggregate().equals("count")) {
				projections.add(Projections.count(aggregate.getField()), alias);
			} else if (aggregate.getAggregate().equals("sum")) {
				projections.add(Projections.sum(aggregate.getField()), alias);
			} else if (aggregate.getAggregate().equals("average")) {
				projections.add(Projections.avg(aggregate.getField()), alias);
			} else if (aggregate.getAggregate().equals("min")) {
				projections.add(Projections.min(aggregate.getField()), alias);
			} else if (aggregate.getAggregate().equals("max")) {
				projections.add(Projections.max(aggregate.getField()), alias);
			}
		}
		return projections;
	}

	private List<?> group(final Criteria criteria, final Session session,
			final Class<?> clazz) {
		List<?> result = new ArrayList<Object>();
		List<GroupDescriptor> group = getGroup();

		if (group != null && !group.isEmpty()) {
			try {
				result = groupBy(criteria.list(), group, clazz, session,
						new ArrayList<SimpleExpression>());
			} catch (IllegalAccessException | IllegalArgumentException
					| InvocationTargetException | HibernateException
					| IntrospectionException e) {

				e.printStackTrace();
			}
		}
		return result;
	}

	private static long total(Criteria criteria) {
		long total = Long.parseLong(criteria
				.setProjection(Projections.rowCount()).uniqueResult()
				.toString());

		criteria.setProjection(null);
		criteria.setResultTransformer(Criteria.ROOT_ENTITY);

		return total;
	}

	private static void page(Criteria criteria, int take, int skip) {
		criteria.setMaxResults(take);
		criteria.setFirstResult(skip);
	}

	public DataSourceResult toDataSourceResult(Session session, Class<?> clazz) {
		Criteria criteria = session.createCriteria(clazz);

		filter(criteria, getFilter(), clazz);

		long total = total(criteria);

		sort(criteria, sortDescriptors());

		page(criteria, getTake(), getSkip());

		DataSourceResult result = new DataSourceResult();

		result.setTotal(total);

		List<GroupDescriptor> groups = getGroup();

		if (groups != null && !groups.isEmpty()) {
			result.setData(group(criteria, session, clazz));
		} else {
			result.setData(criteria.list());
		}

		List<AggregateDescriptor> aggregates = getAggregate();
		if (aggregates != null && !aggregates.isEmpty()) {
			result.setAggregates(aggregate(aggregates, getFilter(), session,
					clazz));
		}

		return result;
	}

	private static Map<String, Object> aggregate(
			List<AggregateDescriptor> aggregates, FilterDescriptor filters,
			Session session, Class<?> clazz) {
		Criteria criteria = session.createCriteria(clazz);

		filter(criteria, filters, clazz);

		return calculateAggregates(criteria, aggregates);
	}

	private List<SortDescriptor> sortDescriptors() {
		List<SortDescriptor> sort = new ArrayList<SortDescriptor>();

		List<GroupDescriptor> groups = getGroup();
		List<SortDescriptor> sorts = getSort();

		if (groups != null) {
			sort.addAll(groups);
		}

		if (sorts != null) {
			sort.addAll(sorts);
		}
		return sort;
	}

	public List<GroupDescriptor> getGroup() {
		return group;
	}

	public void setGroup(List<GroupDescriptor> group) {
		this.group = group;
	}

	public List<AggregateDescriptor> getAggregate() {
		return aggregate;
	}

	public void setAggregate(List<AggregateDescriptor> aggregate) {
		this.aggregate = aggregate;
	}

	public static class SortDescriptor {
		private String field;
		private String dir;

		public String getField() {
			return field;
		}

		public void setField(String field) {
			this.field = field;
		}

		public String getDir() {
			return dir;
		}

		public void setDir(String dir) {
			this.dir = dir;
		}

		@Override
		public String toString() {
			return "SortDescriptor [field=" + field + ", dir=" + dir + "]";
		}

	}

	public static class GroupDescriptor extends SortDescriptor {
		private List<AggregateDescriptor> aggregates;

		public GroupDescriptor() {
			aggregates = new ArrayList<AggregateDescriptor>();
		}

		public List<AggregateDescriptor> getAggregates() {
			return aggregates;
		}

		@Override
		public String toString() {
			return "GroupDescriptor [aggregates=" + aggregates + "]";
		}

	}

	public static class AggregateDescriptor {
		private String field;
		private String aggregate;

		public String getField() {
			return field;
		}

		public void setField(String field) {
			this.field = field;
		}

		public String getAggregate() {
			return aggregate;
		}

		public void setAggregate(String aggregate) {
			this.aggregate = aggregate;
		}

		@Override
		public String toString() {
			return "AggregateDescriptor [field=" + field + ", aggregate="
					+ aggregate + "]";
		}

	}

	public static class FilterDescriptor {
		private String logic;
		private List<FilterDescriptor> filters;
		private String field;
		private Object value;
		private String operator;
		private boolean ignoreCase = true;

		public FilterDescriptor() {
			filters = new ArrayList<FilterDescriptor>();
		}

		public String getField() {
			return field;
		}

		public void setField(String field) {
			this.field = field;
		}

		public Object getValue() {
			return value;
		}

		public void setValue(Object value) {
			this.value = value;
		}

		public String getOperator() {
			return operator;
		}

		public void setOperator(String operator) {
			this.operator = operator;
		}

		public String getLogic() {
			return logic;
		}

		public void setLogic(String logic) {
			this.logic = logic;
		}

		public boolean isIgnoreCase() {
			return ignoreCase;
		}

		public void setIgnoreCase(boolean ignoreCase) {
			this.ignoreCase = ignoreCase;
		}

		public List<FilterDescriptor> getFilters() {
			return filters;
		}

		@Override
		public String toString() {
			return "FilterDescriptor [logic=" + logic + ", filters=" + filters
					+ ", field=" + field + ", value=" + value + ", operator="
					+ operator + ", ignoreCase=" + ignoreCase + "]";
		}

	}

	@Override
	public String toString() {
		return "DataSourceRequest [page=" + page + ", pageSize=" + pageSize
				+ ", take=" + take + ", skip=" + skip + ", sort=" + sort
				+ ", group=" + group + ", aggregate=" + aggregate + ", data="
				+ data + ", filter=" + filter + "]";
	}

}

DataSourceResult:

package com.kendoui.spring.models;

import java.util.List;
import java.util.Map;

public class DataSourceResult {
    private long total;
    
    private List<?> data;
    
    private Map<String, Object> aggregates;

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List<?> getData() {
        return data;
    }

    public void setData(List<?> data) {
        this.data = data;
    }

    public Map<String, Object> getAggregates() {
        return aggregates;
    }

    public void setAggregates(Map<String, Object> aggregates) {
        this.aggregates = aggregates;
    }
}

怎麼樣,簡介而美麗吧!這就是設計的力量。很多人,工作的同伴都無視設計,設計無用論很盛行,什麼如果有設計的時間,我早就怎樣怎樣。我只能說,他們太勤快了,工作時不動腦,累的永遠是自己。設計之美就在於能夠讓程式設計師完美的偷懶,懶到骨頭裡,懶惰是聰明的源泉,是設計的動力。

這裡要強調一些細節。主要是kendo ui GridView使用的細節,也是CSDN另位博主 引路蜂未說明的:

1、dataSource的transport成員的parameterMap方法,必須進行覆蓋重寫,這個與後臺spring的mvc對映密切相關。重寫parameterMap方法,才能對後臺提交資料時提交json物件,引數才能正常反序列化!切記!

						"parameterMap" : function(options) {
							return JSON.stringify(options);
						}

2、dataSource的schema成員的model成員,必須定義id屬性,指向實體的ID。否則控制元件自身的修改、刪除、增加操作會混亂,無法正常工作。現象是增加記錄會多出2條,修改記錄也會多出記錄。因為控制元件無法正常識別修改、增加的操作,到底針對的記錄是什麼情況。而取消按鈕又會被識別成刪除操作導致增加或修改過程中取消,記錄被刪除的問題。因此一定要注意model成員的id屬性一定要指定對應的id,否則GridView只能進行查詢操作,不能進行增、刪、改。

"dataSource" : {
					"schema" : {
						"total" : "total",
						"model" : {
							"id" : "objectId",
							"fields" : {
								"objectId" : {
									"type" : "number"
								},
								"age" : {
									"type" : "number"
								},
								"name" : {
									"type" : "string"
								},
								"bdate" : {
									"type" : "date"
								}
							}
						},
3、注意設定GridView自身的下列屬性,以確保開啟服務端分頁、服務端查詢、服務端過濾、服務端分組,也就是我說的介面與後臺的直接聯動。而不是將資料查詢到介面緩衝後,由介面再分頁、過濾、分組!
					"serverSorting" : true,
				"serverPaging" : true,
					"serverGrouping" : true
4、注意對日期欄位的描述設定。通過如下程式碼的設定,日期欄位的過濾器設定,將變為日曆控制元件。便於操作!
{
					"field" : "bdate",
					"title" : "出生日期",
					"filterable" : {
						"ui" : "datetimepicker"
					},
					"format" : "{0:yyyy-MM-dd HH:mm:ss}"
				}

5、注意對最後一列顯示的按鈕的設定。其中name欄位的屬性值是固定的,只有3種。text為外觀顯示的中文,如果不設定的話,會是英文。
{
					"title" : " ",
					"command" : [ {
						"text" : "編輯",
						"name" : "edit"
					}, {
						"text" : "刪除",
						"name" : "destroy"
					} ]
				} 

6、程式碼最後的部分。指定了是直接在行編輯,還是彈出視窗編輯。如果是彈出視窗將inline改成popup即可,個人提倡用popup,因為popup模式下,彈出窗口裡的屬性是所有屬性,列表hidden設定為true的屬性也會顯示在彈出視窗中。這樣可以達到列表顯示簡潔,編輯時又不缺欄位屬性的目的。
"editable" : {
					"mode" : "inline"
				}

7、如果你希望列寬能夠被調整,那麼要設定resizeable為true,但是如果你設定它為真,則必須給所有的列指定width屬性,否則,沒有指定width的列會有無法顯示的情形。從hidden變為顯示時,也會無法呈現!

8、GridView頂部的Toolbar工具條,設定與最後一列兩個按鈕的配置類似,需要自行指定中文。

				"toolbar" : [ {
					"text" : "新增記錄",
					"name" : "create"
				} ],

至於後臺的兩個關鍵類,它山之石可以攻玉,取來直接用即可!很好的模型封裝,無需再改動什麼。要動的是我們的後臺設計實現。也許又有人說,我的查詢是複雜查詢,多表聯合的,肯定必須寫複雜的sql。我只想說,你是否能考慮把它做成一個通用的sql形成檢視,將檢視對映為hibernate實體,然後將檢視實體直接繫結給GridView,不就可以省下很多事!事在人為!設計的力量就是可以讓我們去多思考,用極少量的功耗,實現極美的效果!

未完待續……