Easyui之Datagrid(数据表格)

前言

今天为大家分享的内容是datagrid,数据表格,用来展示表格中的数据!

1、概念

Datagrid是用来展示表格数据的一种组件!

2、常见使用案例

没错,我今天要讲的案例效果就和下面这张图差不多:

在这里插入图片描述
根据使用的不同情况和创建DataGrid的方式,分为以下三种:

1、从现有的表格元素去创建DataGrid,在HTML中定义列、行和数据:

<table class="easyui-datagrid">   
   <thead>   
       <tr>   
           <th data-options="field:'code'">编码</th>   
           <th data-options="field:'name'">名称</th>   
           <th data-options="field:'price'">价格</th>   
      </tr>   
   </thead>   
   <tbody>   
    <tr>   
         <td>001</td><td>名称1</td><td>2323</td>   
    </tr>   
    <tr>   
         <td>002</td><td>名称2</td><td>4612</td>   
        </tr>   
    </tbody>   
</table>  

2、通过table标签创建DataGrid控件,在表格内使用th标签定义列:

<table class="easyui-datagrid" style="width:400px;height:250px"   
 data-options="url:'datagrid_data.json',fitColumns:true,
 singleSelect:true">   
<thead>   
 <tr>   
   <th data-options="field:'code',width:100">编码</th>   
   <th data-options="field:'name',width:100">名称</th>   
   <th data-options="field:'price',width:100,align:'right'">价格</th>   
        </tr>   
    </thead>   
</table> 

3、通过Javascript去创建DataGrid控件:

$('#dg').datagrid({    
    url:'datagrid_data.json',    
    columns:[[    
        {field:'code',title:'代码',width:100},    
        {field:'name',title:'名称',width:100},    
        {field:'price',title:'价格',width:100,align:'right'}    
    ]]    
});  

jsp页面中会使用到这行代码:

<table id="dg"></table> 

3、datagrid属性

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4、datagrid事件

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5、datagrid方法

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

6、案例演示

当然今天重要需要讲解的就是使用js代码去实现数据表格这样一个方式:(也就是上面的第三种)

实现过程分两种:

1、静态html实现

<table id="dg" class="easyui-datagrid" title="Fluid DataGrid" style="width:700px;height:250px"
 data-options="singleSelect:true,collapsible:true,url:'datagrid_data1.json',method:'get'">
<thead>
<tr>
 <th data-options="field:'itemid',resizable:false" width="15%">Item ID(15%)</th>
 <th data-options="field:'productid',resizable:false" width="15%">Product(15%)</th>
 <th data-options="field:'listprice',align:'right',resizable:false" width="15%">List Price(15%)</th>
 <th data-options="field:'unitcost',align:'right',resizable:false" width="15%">Unit Cost(15%)</th>
 <th data-options="field:'attr1',resizable:false" width="25%">Attribute(25%)</th>
<th data-options="field:'status',align:'center',resizable:false" width="15%">Status(15%)</th>
</tr>
</thead>
</table>

重点讲解第二种:

2、js方式实现:

jsp页面代码:
记得是放在body标签下面

<table id="dg"></table>  

datagrid_data1.json:

{"total":28,"rows":[
	{"productid":"FI-SW-01","productname":"Koi","unitcost":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"},
	{"productid":"K9-DL-01","productname":"Dalmation","unitcost":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"},
	{"productid":"RP-SN-01","productname":"Rattlesnake","unitcost":12.00,"status":"P","listprice":38.50,"attr1":"Venomless","itemid":"EST-11"},
	{"productid":"RP-SN-01","productname":"Rattlesnake","unitcost":12.00,"status":"P","listprice":26.50,"attr1":"Rattleless","itemid":"EST-12"},
	{"productid":"RP-LI-02","productname":"Iguana","unitcost":12.00,"status":"P","listprice":35.50,"attr1":"Green Adult","itemid":"EST-13"},
	{"productid":"FL-DSH-01","productname":"Manx","unitcost":12.00,"status":"P","listprice":158.50,"attr1":"Tailless","itemid":"EST-14"},
	{"productid":"FL-DSH-01","productname":"Manx","unitcost":12.00,"status":"P","listprice":83.50,"attr1":"With tail","itemid":"EST-15"},
	{"productid":"FL-DLH-02","productname":"Persian","unitcost":12.00,"status":"P","listprice":23.50,"attr1":"Adult Female","itemid":"EST-16"},
	{"productid":"FL-DLH-02","productname":"Persian","unitcost":12.00,"status":"P","listprice":89.50,"attr1":"Adult Male","itemid":"EST-17"},
	{"productid":"AV-CB-01","productname":"Amazon Parrot","unitcost":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"}
]}

js代码:

$(function() {
	$('#dg').datagrid({    
	url:'datagrid_data1.json';
    columns:[[    
        {field:'productid',title:'产品id',width:100},    
        {field:'productname',title:'名称',width:100},    
        {field:'unitcost',title:'价格',width:100},
   ]]    
}); 

效果:

在这里插入图片描述

案例2:

以结果为导向,需要实现以下这张图的(模糊查询、分页、数据展示)

最终实现效果:

在这里插入图片描述
模糊查询的效果:
(根据书名进行模糊查询)

在这里插入图片描述
查询后的结果:

在这里插入图片描述

使用到的数据库表格数据:

在这里插入图片描述

首先分析需求:

1、需要实现分页

2、需要展示数据表格的数据

3、需要能够进行模糊查询

代码展示及分析:

Book类:

写表格数据对应的属性、构造方法、构造函数、toString方法

package com.wangqiuping.entity;

import java.sql.Timestamp;

public class Book {

private  long id;
private  String name;
private  String pinyin;
private  long cid;
private  String  author;
private  float  price;
private  String image;
private  String publishing;
private  String description;
private  int  state;
private  Timestamp deployTime;
private  int sales;
public long getId() {
	return id;
}
public void setId(long id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getPinyin() {
	return pinyin;
}
public void setPinyin(String pinyin) {
	this.pinyin = pinyin;
}
public long getCid() {
	return cid;
}
public void setCid(long cid) {
	this.cid = cid;
}
public String getAuthor() {
	return author;
}
public void setAuthor(String author) {
	this.author = author;
}
public float getPrice() {
	return price;
}
public void setPrice(float price) {
	this.price = price;
}
public String getImage() {
	return image;
}
public void setImage(String image) {
	this.image = image;
}
public String getPublishing() {
	return publishing;
}
public void setPublishing(String publishing) {
	this.publishing = publishing;
}
public String getDescription() {
	return description;
}
public void setDescription(String description) {
	this.description = description;
}
public int getState() {
	return state;
}
public void setState(int state) {
	this.state = state;
}
public Timestamp getDeployTime() {
	return deployTime;
}
public void setDeployTime(Timestamp deployTime) {
	this.deployTime = deployTime;
}
public int getSales() {
	return sales;
}
public void setSales(int sales) {
	this.sales = sales;
}
public Book(long id, String name, String pinyin, long cid, String author, float price, String image, String publishing,
		String description, int state, Timestamp deployTime, int sales) {
	super();
	this.id = id;
	this.name = name;
	this.pinyin = pinyin;
	this.cid = cid;
	this.author = author;
	this.price = price;
	this.image = image;
	this.publishing = publishing;
	this.description = description;
	this.state = state;
	this.deployTime = deployTime;
	this.sales = sales;
}
public Book() {
	super();
}
public Book(long id, String name, String pinyin) {
	super();
	this.id = id;
	this.name = name;
	this.pinyin = pinyin;
}
@Override
public String toString() {
	return "Book [id=" + id + ", name=" + name + ", pinyin=" + pinyin + ", cid=" + cid + ", author=" + author
			+ ", price=" + price + ", image=" + image + ", publishing=" + publishing + ", description=" + description
			+ ", state=" + state + ", deployTime=" + deployTime + ", sales=" + sales + "]";
}
}

注意属性字段名和数据库字段名保持一致!

BookDao类:

模糊查询、查询所有以及测试是否能遍历输出数据的方法

package com.wangqiuping.dao;

import java.sql.SQLException;
import java.util.List;
import com.wangqiuping.entity.Book;
import com.wangqiuping.util.BaseDao;
import com.wangqiuping.util.PageBean;
import com.wangqiuping.util.StringUtils;

public class BookDao extends BaseDao<Book>{

public  List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
	String name=book.getName();
	String sql="select * from t_easyui_book where true";
	if(StringUtils.isNotBlank(name)){
	  sql +=" and name like'%"+name+"%'";
	}
	return executeQuery(sql,Book.class,pageBean);
}
	
public static void main(String[] args) throws InstantiationException, IllegalAccessException, SQLException {
	BookDao	bookDao=new BookDao();
	Book book=new Book();
	List<Book> list = bookDao.list(book,null);
	for (Book b: list) {
		System.out.println(b);
	}
 }
}

DataGridResult类:
工具类
协助BookAction一起得出总记录数、每一页显示多少行数
同时还有一个实例化方法

package com.wangqiuping.util;

public class DataGridResult<T>{

private  String total;
private  T    rows;
 
public String getTotal() {
	return total;
}
public void setTotal(String total) {
	this.total = total;
}
public T getRows() {
	return rows;
}
public void setRows(T rows) {
	this.rows = rows;
}
private  DataGridResult(String total, T rows) {
	super();
	this.total = total;
	this.rows = rows;
}
private  DataGridResult() {
	super();
}
    
public  static <T>  DataGridResult ok(String total,T rows){
	return new DataGridResult<T>(total, rows);
}	
}

BookAction类:

用来处理业务逻辑

考虑两个问题:totals和rows数据从哪来
totals : pageBean中的totals属性
rows : 每一页展示的行数

package com.wangqiuping.action;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangqiuping.dao.BookDao;
import com.wangqiuping.entity.Book;
import com.wangqiuping.framework.ActionSupport;
import com.wangqiuping.framework.ModelDriven;
import com.wangqiuping.util.DataGridResult;
import com.wangqiuping.util.PageBean;
import com.wangqiuping.util.ResponseUtil;

public class BookAction extends ActionSupport implements ModelDriven<Book>{

	private  Book  book=new Book();
	private  BookDao bookDao=new BookDao();
	
	@Override
	public Book getModel() {
		// TODO Auto-generated method stub
		return book;
	}

	
	public String datagrid(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		PageBean pageBean=new PageBean();
		try {
	     List<Book> list = this.bookDao.list(book, pageBean);
		  ResponseUtil.writeJson(resp,DataGridResult.ok(pageBean.getTotal()+"",list));
		}catch (InstantiationException e) {
			e.printStackTrace();
		}catch (IllegalAccessException e) {
			e.printStackTrace();
		}catch (SQLException e) {
		}
		return null;
	}
	

	private String ok(int total) {
		// TODO Auto-generated method stub
		return null;
	}


	public static void main(String[] args) throws JsonProcessingException {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("total",28);
		List<Book> asList = Arrays.asList(new Book(1,"x1","x1"),new Book(2,"x2","x2"),new Book(3,"x3","x3"));
		map.put("rows",asList);
		//将map集合转换成json
		ObjectMapper om=new ObjectMapper();
		String jsonstr = om.writeValueAsString(map);
	    System.out.println(jsonstr);
	}
}

第一种展示最终数据表格中数据和分页的方式

//		  Map<String,Object> map=new HashMap<String,Object>();
//		  map.put("totals",pageBean.getTotal());
//		  map.put("rows",list);
//		  ResponseUtil.writeJson(resp,map);

第二种展示最终数据表格中数据和分页的方式

 List<Book> list = this.bookDao.list(book, pageBean);
ResponseUtil.writeJson(resp,DataGridResult.ok(pageBean.getTotal()+"",list));

相较之下,第二种方式更加简便灵活!

需要配置的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<config>	
  <action path="/book"  type="com.wangqiuping.action.BookAction">
  </action>
</config>

js代码:

$(function() {
	var ctx=$("#ctx").val();
	$('#dg').datagrid({    
    url:ctx+'/book.action?methodName=datagrid', 
    toolbar:'#tb',
    pagination:true,//用来分页的属性 通过js实现
    columns:[[    
        {field:'id',title:'id',width:100},    
        {field:'name',title:'书籍名称',width:200},    
        {field:'pinyin',title:'拼音',width:100},
        {field:'cid',title:'书籍类别',width:100},
        {field:'author',title:'作者',width:100},
        {field:'price',title:'价格',width:100},
        {field:'image',title:'图片',width:300},
        {field:'publishing',title:'出版',width:100},
        {field:'description',title:'描述',width:100},
        {field:'state',title:'国家',width:100},
        {field:'sales',title:'销量',width:100},
        {field:'deployTime',title:'时间',width:100},
   ]]    
});  
	
	//点击搜索按钮完成按书名进行模糊查询
	$("#btn-search").click(function() {
//		alert(111);
		$('#dg').datagrid('load', {    
		    name: $("#namebox").val()     
		});  
	})	;	
})

1、其中pagination是boolean类型,如果为true,表示分页,反之不分页!
2、模糊查询中的name是表示字段名,namebox是表示jsp页面传过来的id值!不要弄错了!!
3、没有分号结尾!

 pagination:true

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">
<!-- 写全局样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">   
<!-- 定义图标的样式-->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/themes/icon.css">   
<!--组件库源文件的js文件-->
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>  
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>   
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/book.js"></script>   
<title>book增删改查</title>
</head>
<body>
<input type="hidden" id="ctx" value="${pageContext.request.contextPath}"/>
<div id="tb">
<input class="easyui-textBox" id="namebox" name="name" style="width: 20%;padding-left:1-px " data-options="label:'书名',required:true">
<a id="btn-search" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit'">搜索</a>
<a id="btn-add" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-help'">新增</a>
</div>
<table id="dg"></table>  
</body>
</html>

注意css样式和js引入的先后顺序!

toolbar: 通过数组定义工具栏:

$('#dg').datagrid({
	toolbar: [{
		iconCls: 'icon-edit',
		handler: function(){alert('编辑按钮')}
	},'-',{
		iconCls: 'icon-help',
		handler: function(){alert('帮助按钮')}
	}]
});

toolbar:

	toolbar: '#tb'

个人推荐使用第二种!!

使用一些参数查询数据:

$('#dg').datagrid('load', {    
    name: 'easyui',    
    address: 'ho'   
});  

其中name和address都是字段名!

注意:js中属性与属性之间用逗号隔开!

7、为什么使用datagrid

1、DataGrid提供了丰富的选择、排序、分组和编辑数据的功能支持。

2、DataGrid的设计用于缩短开发时间,并且使开发人员不需要具备特定的知识。

3、DataGrid是轻量级的且功能丰富。单元格合并、多列标题、冻结列和页脚只是其中的一小部分功能。

总结

之所以重点讲解了使用js方式去实现datagrid数据表格,是因为使用静态html的方式需要嵌套多个c:foreach,代码会非常繁琐,而使用js方式去动态展示数据表格中的数据会更加便捷灵活!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45464930/article/details/106942831