JQuery easyui datagrid

 在easyui官方网站http://www.jeasyui.com/下载jquery-easyui项目

         前阶段使用了easyui datagrid进行了表格显示,个人觉得easyui datagrid的使用和上一篇文章介绍的JQuery paganition的使用大同小异,后端接收前台传递过来的参数信息,比如分页信息(查询的页码数,每页显示的记录数),排序信息(排序的字段,排序顺序)等,后端进行查询后,通常以XML或JSON格式进行返回,返回之后把查询得到的数据显示到页面上。

下面是一个使用easyui datagrid的简单例子,能够进行分页和排序。

实体类User

package com.guchao.datagrid.entity;

import java.util.Date;

public class User {

	private int id;
	
	private String username;
	
	private int age;
	
	private Date birthday;

	public User(){}
	public User(int id, String username, int age, Date birthday) {
		this.id = id;
		this.username = username;
		this.age = age;
		this.birthday = birthday;
	}

	public int getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getAge() {
		return age;
	}

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

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}

 

请求的Servlet

package com.guchao.datagrid.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

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

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;

import com.guchao.datagrid.entity.Message;
import com.guchao.datagrid.entity.User;
import com.guchao.datagrid.util.JsonDateValueProcessor;

public class TestEasyUiDatagridServlet extends HttpServlet {

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

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//页码数
		String pageNum = req.getParameter("page");
		int pageNo = 0;
		if(pageNum != null && !pageNum.trim().equals("")){
			pageNo =Integer.parseInt(pageNum);
		}
		//每页显示记录数
		String pageSize = req.getParameter("rows");
		int size = 0;
		if(pageSize != null && !pageSize.trim().equals("")){
			size =Integer.parseInt(pageSize);
		}
		String sortName = req.getParameter("sort");//排序字段
		String sortOrder = req.getParameter("order");//排序的顺序
		System.out.println("sortName="+sortName+",sortOrder="+sortOrder+",page="+pageNo+",row="+size);
		
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		int count = 0;
		List<Object> data = new LinkedList<Object>();
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myhibernate", "root", "mysql");
			String countSql = "select count(*) from t_user";
			stmt = con.createStatement();
			rs = stmt.executeQuery(countSql);
			if(rs.next()){
				count = rs.getInt(1);
			}
			String sql = "select id,username,age,birthday from t_user ";
			if(StringUtils.isNotBlank(sortName) && StringUtils.isNotBlank(sortOrder)){
				sql += " order by "+sortName+" "+sortOrder; 
			}
			sql += " limit "+(pageNo-1)*size+","+size;
			System.out.println(sql);
			rs = stmt.executeQuery(sql);
			while(rs.next()){
				User u = new User(rs.getInt("id"),rs.getString("username"),rs.getInt("age"),rs.getDate("birthday"));
				data.add(u);
				System.out.println(rs.getInt("id")+","+rs.getString("username")+","+rs.getInt("age")+","+rs.getDate("birthday"));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} finally{
			try {
				rs.close();
				stmt.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		Message m = new Message();
		m.setTotal(count);
		m.setRows(data);
		
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd"));
		JSONObject jsonObject = JSONObject.fromObject(m, config);
		System.out.println(jsonObject.toString());
		resp.getWriter().write(jsonObject.toString());
	}
}

 

返回的JSON类

package com.guchao.datagrid.entity;

import java.util.List;

public class Message {

	private int total;
	
	private List<Object> rows;

	public int getTotal() {
		return total;
	}

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

	public List<Object> getRows() {
		return rows;
	}

	public void setRows(List<Object> rows) {
		this.rows = rows;
	}
}

 

日期类型的处理类

package com.guchao.datagrid.util;

import java.text.SimpleDateFormat;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class JsonDateValueProcessor implements JsonValueProcessor {

	public static final String Default_DATE_PATTERN = "yyyy-MM-dd";  
	private SimpleDateFormat dateFormat;
	
	public JsonDateValueProcessor(String datePattern){
		try {  
	         dateFormat = new SimpleDateFormat(datePattern);  
	     } catch (Exception e) {
	         dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);   
	     }
	}
     
	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value);
	}
	
	private Object process(Object value) {  
        if (value == null) {  
            return "";  
        } else {  
            return dateFormat.format(value);  
        }  
    } 
}

 

JSP页面

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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>My JSP 'index.jsp' starting page</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<link rel="stylesheet" href="jquery-easyui-1.3.2/themes/default/easyui.css">
	<link rel="stylesheet" href="jquery-easyui-1.3.2/themes/icon.css">
	<link rel="stylesheet" href="jquery-easyui-1.3.2/demo/demo.css">
	<script type="text/javascript" src="jquery-easyui-1.3.2/jquery-1.8.0.min.js"></script>
	<script type="text/javascript" src="jquery-easyui-1.3.2/jquery.easyui.min.js"></script>
  </head>
  
  <body>
    <h2>Basic DataGrid</h2>
	<div class="demo-info">
		<div class="demo-tip icon-tip"></div>
		<div>The DataGrid is created from markup, no JavaScript code needed.</div>
	</div>
	<div style="margin:10px 0;"></div>
	
	<table class="easyui-datagrid" title="Basic DataGrid" style="width:700px;height:250px"
			data-options="singleSelect:true,collapsible:true,url:'testEasyUiDatagrid.do'" 
			pagination="true">
		<thead>
			<tr>
				<th data-options="field:'id',width:80,sortable:true">id</th>
				<th data-options="field:'username',width:100,sortable:true">username</th>
				<th data-options="field:'age',width:80,align:'right'">age</th>
				<th data-options="field:'birthday',width:80,align:'right'">birthday</th>
			</tr>
		</thead>
	</table>
  </body>
</html>

 web.xml

<servlet>
		<servlet-name>TestEasyUiDatagrid</servlet-name>
		<servlet-class>com.guchao.datagrid.servlet.TestEasyUiDatagridServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>TestEasyUiDatagrid</servlet-name>
		<url-pattern>/testEasyUiDatagrid.do</url-pattern>
	</servlet-mapping>

 

页面的效果图和项目结构图参见附件!更多信息请参考easyui官方网站http://www.jeasyui.com/

 

你可能感兴趣的:(jquery easyui)