DataGrid的增删改

前言

今天为大家分享的知识点是使用datagrid数据表格进行增删改的操作,至于查询的话,我之前的博客就有分享:

datagrid数据表格实现查询

正常效果演示

在这里插入图片描述

增加效果演示

增加一条数据:

在这里插入图片描述

模糊查询一下,可以看到增加进去的数据:

在这里插入图片描述

修改效果演示

修改前:

把爱的种子改成种子,把时间修改一下!

在这里插入图片描述
修改后:

在这里插入图片描述

删除效果演示

把种子这条数据进行删除:

在这里插入图片描述
删除后:
点击确定后得到删除的结果:

在这里插入图片描述
因为样式中data-options中可对窗体中选项设置是否必填 以及是什么格式

data-options:required或者validateType 设置验证类型

所以在增加或者修改数据的时候 会进行相关的提示!

工具类和jar依赖

在这里插入图片描述
jar依赖:
在这里插入图片描述

代码展示

首先是后台增删改的dao方法:

//增加
public  int  add(Book  book) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
	String  sql="insert into t_easyui_book values(null,?,?,?,?,?,?,?,?,?,?,?)";
	//pinyin的属性值不是从jsp传递过来的  给书名设置全拼
	book.setPinyin(PinYinUtil.getAllPingYin(book.getName()));
	return  super.executeUpdate(sql,book,new String[] {"name","pinyin","cid","author","price","image","publishing","description","state","deployTime","sales"});
}		

//修改
public int edit(Book book) throws NoSuchFieldException, SecurityException, IllegalArgumentException,
IllegalAccessException, SQLException {
book.setPinyin(PinYinUtil.getAllPingYin(book.getName()));
String sql = "update  t_easyui_book  set  name=?,pinyin=?,cid=?,author=?,price=?,image=?,publishing=?,description=?,state=?,deployTime=?,sales=? where id=?";
return super.executeUpdate(sql, book, new String[] { "name", "pinyin", "cid", "author", "price", "image", "publishing", "description", "state", "deployTime", "sales", "id" });
}


//删除
public  int del(Book book) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
	String  sql="delete from t_easyui_book where id=?";
	return super.executeUpdate(sql,book,new String[] {"id"});
}

注意sql语句不要写错了!

在使用action类处理业务逻辑之前,需要使用到Result工具类进行配置结果码 msg信息 data数据 用来提示操作成功!

package com.wangqiuping.util;

public class Result<T> {
	
	private int code;
	private String msg;
	private T data;
	
	public static Result SUCCESS=new Result<>(200,"操作成功!");
	public static <T> Result ok(T data) {
		return new Result(data);
	}
	
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public T getData() {
		return data;
	}
	public void setData(T data) {
		this.data = data;
	}
	private Result(int code, String msg, T data) {
		super();
		this.code = code;
		this.msg = msg;
		this.data = data;
	}
	private Result() {
		super();
	}
	@Override
	public String toString() {
		return "Result [code=" + code + ", msg=" + msg + ", data=" + data + "]";
	}
	private Result(int code, String msg) {
		super();
		this.code = code;
		this.msg = msg;
	}

	private Result(T data) {
		super();
		this.data = data;
	}	
}

其次是用来处理业务逻辑的action类:

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;
import com.wangqiuping.util.Result;

public class BookAction extends ActionSupport implements ModelDriven<Book>{

	private  Book  book=new Book();
	private  BookDao bookDao=new BookDao();
	
	@Override
	public Book getModel() {
		return book;
	}

	
	public String datagrid(HttpServletRequest req,HttpServletResponse resp) throws Exception {
//		考虑两个问题:totals和rows数据从哪来
//		totalspageBean中的totals属性   rows 每一页展示的行数
		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;
	}
	

	
//	删除
	public String del(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		try {
			int del = this.bookDao.del(book);
			ResponseUtil.writeJson(resp,Result.SUCCESS);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;	
	}
	

	
	//修改、增加合二为一
	public String save(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		try {
			if(book.getId()!=0) {
				this.bookDao.edit(book);
			}
			else {
				this.bookDao.add(book);
			}
			ResponseUtil.writeJson(resp, Result.SUCCESS);

		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		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);
	}
}

相比较于使用servlet获取jsp页面的数据,这里使用到的easyui是不需要进行页面跳转的 只需要使用模态框弹出一个窗体 进行局部刷新 然后调用处理业务逻辑中的增加和修改合二为一的方法 进行判断是否增加或者修改 如果模态框中没有值 进行增加 反之 进行数据回显 进行修改

//修改、增加合二为一
	public String save(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		try {
			if(book.getId()!=0) {
				this.bookDao.edit(book);
			}
			else {
				this.bookDao.add(book);
			}
			ResponseUtil.writeJson(resp, Result.SUCCESS);

		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

js代码:

删除的话 使用的js的方法 需要获取选中行的ID
根据获取到的ID进行删除

$(function() {
	var ctx=$("#ctx").val();
	$('#dg').datagrid({    
    url:ctx+'/book.action?methodName=datagrid', 
    toolbar:'#tb',
    pagination:true,//用来分页的属性 通过js实现
    singleSelect:true,
    columns:[[    
        {field:'id',title:'id',width:100},    
        {field:'name',title:'书籍名称',width:100},    
        {field:'pinyin',title:'拼音',width:100},
        {field:'cid',title:'书籍类别',width:100},
        {field:'author',title:'作者',width:100},
        {field:'price',title:'价格',width:100},
        {field:'image',title:'图片',width:200},
        {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},
        {field:'操作',title:'操作',width:100,formatter: function(value,row,index){
			return '<a href="javascript:void(0)" οnclick="edit()">修改</a>&nbsp;&nbsp;<a href="javascript:void(0)" οnclick="del()">删除</a>'
          }
		}
     ]]      
});  
	
	//点击搜索按钮完成按书名进行模糊查询
	$("#btn-search").click(function() {
//		alert(111);
		$('#dg').datagrid('load', {    
		    name: $("#namebox").val()     
		});  
	});	
	
	//给新增按钮绑定点击事件
	$("#btn-add").click(function(){
		//需要打开dialog窗体
		$("#dd").dialog('open');
	});
	
	
	$("#btn-save").click(function(){
		$('#ff').form('submit', {    
			url:ctx+'/book.action?methodName=save',    
		    success:function(data){    
		    	data = eval('(' + data + ')');
		    	if(data.code==200){
		    		 alert(data.msg);
		    		 //刷新
		    		 $('#ff').form('clear');
		    		 //关闭模态框
		    		 $('#dd').dialog('close');
		    		//刷新datagrid的数据
		    		 $('#dg').datagrid('reload');
		    }
	      }    
	   });
	});
})


    //修改方法
    function edit() {
	// alert('测试一下');
	// 数据回显,将选中的datatgrid值进行回显到form表单
	var row = $("#dg").datagrid('getSelected');
	if (row) {
		$("#ff").form('load',row);
   //让用户看到from表单
		$("#dd").dialog('open');
	}
}


//删除
function del(){
//	从获取到行对象开始
	var row =$('#dg').datagrid('getSelected');
//	不为空的话就进行下一步处理
	 if(row){
//			加载ajax进行局部刷新
		$.ajax({
//          加载资源
			url:$("#ctx").val()+'/book.action?methodName=del&&id='+row.id,
//			得到成功函数返回的值
			success:function(data){ 
//				将括号内的表达式('data')转化为对象
				data = eval('(' + data + ')');
		        if(data.code == 200){
		    	   alert(data.msg);
//		    	          刷新数据
		    	   $('#dg').datagrid('reload'); 
		       }
		    } 
		});
	 }
}

修改的js中记得在数据回显后重新刷新数据!

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/addBook.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="namebox" 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>  

	<div id="dd" class="easyui-dialog" title="书籍信息编辑窗体" style="width:400px;height:400px;"   
	    data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#fbtns'">   
	   
	    <form id="ff" method="post"> 
	  	    
		  <input type="hidden" name="id" />
		      
		     <div>   
		        <label for="name">书名:</label>   
		        <input class="easyui-validatebox" type="text" id="name" name="name" data-options="required:true" />   
		    </div>    
		    
		     
		    <div>   
		        <label for="cid">类型id:</label>   
		        <input class="easyui-validatebox" type="text" name="cid" data-options="required:true" />   
		    </div>  
		    
		    <div>   
		        <label for="author">作者:</label>   
		        <input class="easyui-validatebox" type="text" name="author" data-options="required:true" />   
		    </div>  
		    <div>   
		        <label for="price">价格:</label>   
		        <input class="easyui-validatebox" type="text" name="price" data-options="required:true" />   
		    </div>  
		    <div>   
		        <label for="image">图片:</label>   
		        <input class="easyui-validatebox" type="text" name="image" data-options="required:true" />   
		    </div> 
		    <div>   
		        <label for="publishing">出版社:</label>   
		        <input class="easyui-validatebox" type="text" name="publishing" data-options="required:true" />   
		    </div> 
		    
		    <div>   
		        <label for="description">描述:</label>   
		        <input class="easyui-validatebox" type="text" name="description" data-options="required:true" />   
		    </div> 
		    
		    <div>   
		        <label for="state">状态:</label>   
		        <input class="easyui-validatebox" type="text" name="state" data-options="required:true" />   
		    </div> 
		    
		    <div>   
		        <label for="deployTime">时间:</label>   
		        <input class="easyui-validatebox" type="text" name="deployTime" data-options="required:true" />   
		    </div> 
		    
		    <div>   
		        <label for="sales">销量:</label>   
		        <input class="easyui-validatebox" type="text" name="sales" data-options="required:true" />   
		    </div>    
		</form>  
		
	</div> 
	
	<div id="fbtns">
		<a id="btn-save"   href="#" class="easyui-linkbutton"   data-options="iconCls:'icon-search',plain:true">保存</a>
		<a id="btn-cancel" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true">取消</a>
	</div>
</body>
</html>

注意要点

1、写这些代码的时候,可能会有比较严重的缓存问题,尤其是在修改了js代码之后,Ctrl+shift+delete快捷键清空浏览器缓存!

2、找到工具栏上面的project------>Clean清空eclipse缓存!

总结

使用easyui中datagrid组件以及from组件的方式,实现增删改的操作,其中也借助了后台中的工具类得以将前端数据显示、并且easyui中已经有data-options属性、可以用来校验,不用再写正则表达式校验,并且easyui中不需要页面跳转,只需要使用模态框弹出窗体 局部刷新就好 从而更加方便快捷!

猜你喜欢

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