kendo-ui中kendoGrid的用法

本文实现了一个kendo-ui中kendoGrid从servlet中获取数据,从而显示出来的例子。

程序结构如下:

kendo-ui中kendoGrid的用法_第1张图片

User.java代码如下:
package com.kendoui.bean;

import com.kendoui.uitls.Generator;

public class User {
	
	private int id;
	
	private String firstName;
	
	private String lastName;
	
	private String city;
	
	private String title;
	
	private int age;
	
	public User(){
		id = Generator.getId();
		firstName = Generator.getFirstName();
		lastName =  Generator.getLastName();
		city = Generator.getCity();
		title = Generator.getTitle();
		age = Generator.getAge();
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}



DataServlet.java代码如下:

package com.kendoui.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kendoui.bean.User;
import com.kendoui.uitls.JSONBinder;

public class DataServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	JSONBinder jsonBinder = JSONBinder.buildNormalBinder();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<User> userList = new ArrayList<User>();
		System.out.println("==========================================");
		for(int i=0;i<20;i++){
			userList.add(new User());
		}
		System.out.println("servlet has been invoked!");
		response.getWriter().write(jsonBinder.toJson(userList));
		
	}
}



Generator.java的代码如下:
package com.kendoui.uitls;

/**
 * 用来随机生成User类的属性
 * @author yangjianzhou
 *
 */
public class Generator {
	
	private static int id = 0;
	private static String[]  firstNames = {"Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne", "Nige"};
	private static String[]  lastNames = {"Davolio", "Fuller", "Leverling", "Peacock", "Buchanan", "Suyama", "King", "Callahan", "Dodsworth", "White"};
	private static String[]  cities = {"Seattle", "Tacoma", "Kirkland", "Redmond", "London", "Philadelphia", "New York", "Seattle", "London", "Boston"};
	private static String[]  titles = {"Accountant", "Vice President, Sales", "Sales Representative", "Technical Support", "Sales Manager", "Web Designer",
		    "Software Developer", "Inside Sales Coordinator", "Chief Techical Officer", "Chief Execute Officer"};
	
	public Generator(){
		
	}
	
	public static synchronized int getId(){
		id ++;
		return id;
	}
	
	public static String getFirstName(){
		return firstNames[(int)Math.floor(Math.random()*firstNames.length)];
	}
	
	public static String getLastName(){
		return lastNames[(int)Math.floor(Math.random()*lastNames.length)];
	}
	
	public static String getCity(){
		return cities[(int)Math.floor(Math.random()*cities.length)];
	}
	
	public static String getTitle(){
		return titles[(int)Math.floor(Math.random()*titles.length)];
	}
	
	public static int getAge(){
		return 20+(int)(Math.random()*30);
	}
	
}



JSONBinder.java是对JSON数据的一些操作,例如生成JSON数据,将数组、List等装换为JSON

格式数据。该类是引用别人的。

代码如下:
package com.kendoui.uitls;

/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: JsonBinder.java 1216 2010-09-12 13:52:48Z calvinxiu $
 */

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Jackson的简单封装.
 * 
 * @author calvin
 */
public class JSONBinder {

	private static Logger logger = LoggerFactory.getLogger(JSONBinder.class);

	private ObjectMapper mapper;

	public JSONBinder(Inclusion inclusion) {
		mapper = new ObjectMapper();
		mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
		//设置输出包含的属性
		mapper.getSerializationConfig().setSerializationInclusion(inclusion);
		//设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
		mapper.getDeserializationConfig().set(
				org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	/**
	 * 创建输出全部属性到Json字符串的Binder.
	 */
	public static JSONBinder buildNormalBinder() {
		return new JSONBinder(Inclusion.ALWAYS);
	}

	/**
	 * 创建只输出非空属性到Json字符串的Binder.
	 */
	public static JSONBinder buildNonNullBinder() {
		return new JSONBinder(Inclusion.NON_NULL);
	}

	/**
	 * 创建只输出初始值被改变的属性到Json字符串的Binder.
	 */
	public static JSONBinder buildNonDefaultBinder() {
		return new JSONBinder(Inclusion.NON_DEFAULT);
	}

	/**
	 * 如果JSON字符串为Null或"null"字符串,返回Null.
	 * 如果JSON字符串为"[]",返回空集合.
	 * 
	 * 如需读取集合如List/Map,且不是List<String>这种简单类型时使用如下语句:
	 * List<MyBean> beanList = binder.getMapper().readValue(listString, new TypeReference<List<MyBean>>() {});
	 */
	public <T> T fromJson(String jsonString, Class<T> clazz) {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}

		try {
			return mapper.readValue(jsonString, clazz);
		} catch (IOException e) {
			logger.warn("parse json string error:" + jsonString, e);
			return null;
		}
	}

	/**
	 * 如果对象为Null,返回"null".
	 * 如果集合为空集合,返回"[]".
	 */
	public String toJson(Object object) {

		try {
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			logger.warn("write to json string error:" + object, e);
			return null;
		}
	}

	/**
	 * 设置转换日期类型的format pattern,如果不设置默认打印Timestamp毫秒数.
	 */
	@SuppressWarnings("deprecation")
	public void setDateFormat(String pattern) {
		if (StringUtils.isNotBlank(pattern)) {
			DateFormat df = new SimpleDateFormat(pattern);
			mapper.getSerializationConfig().setDateFormat(df);
			mapper.getDeserializationConfig().setDateFormat(df);
		}
	}

	/**
	 * 取出Mapper做进一步的设置或使用其他序列化API.
	 */
	public ObjectMapper getMapper() {
		return mapper;
	}
}



index.jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Virtualization of local data</title>

<link href="css/examples-offline.css" rel="stylesheet">
<link href="css/kendo.common.min.css" rel="stylesheet">
<link href="css/kendo.default.min.css" rel="stylesheet">

<script src="javascript/jquery.min.js"></script>
<script src="javascript/kendo.web.min.js"></script>
<script src="javascript/console.js"></script>
<script src="javascript/people.js"></script>
</head>
<body>
<div id="loading" class="demo-section" style="text-align: center">
		Generating test data...</div>
	<div id="example" class="k-content">

		<div id="grid"></div>
		<script>
                $("#loading").click(function() {
                    generatePeople(10, function(data) {
                        $("#loading").hide();
                		$.ajax({
                    		type:"POST",
                    		dataType:"JSON",
                        	url:"dataServlet",
                           success:function(result){
                        	  var data = result;
                            $("#grid").kendoGrid({
                            	dataSource:{
                            		data:data
                            	},
                            	height: 530,
                                scrollable: {
                                    virtual: true
                                },
                                columns: [ { field: "id", title: "ID", width: "70px" },
                                    { field: "firstName", title: "First Name", width: "130px" },
                                    { field: "lastName", title: "Last Name", width: "130px" },
                                    { field: "city", title: "City", width: "130px" },
                                    { field: "title", title: "Title", width: "130px" },
                                    { field: "age", title: "Age", width: "130px" },
                                ]
                            });
                           },
                           error:function(){
                        	   window.alert('error');
                           }
                		});
                            
                    });
                });
            </script>
	</div>

</body>
</html>



web.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>kendoui</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<servlet>
		<servlet-name>dataServlet</servlet-name>
		<servlet-class>com.kendoui.servlet.DataServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>dataServlet</servlet-name>
		<url-pattern>/dataServlet</url-pattern>
	</servlet-mapping>
</web-app>


运行结果如下:



点击Generating test data之后显示如下:

kendo-ui中kendoGrid的用法_第2张图片


你可能感兴趣的:(grid)