easyui 的datagrid增删改

前言

接着上一篇的内容继续,上一篇说了查询,这次完成 增删改 的功能,可以通过增删改的功能学习dialog模态框组件form组件

一、自动生成拼音的工具

在我数据库表的列字段里有个拼音,我们可以通过工具类自动生成,则需要到这个拼音工具类跟jar包
在这里插入图片描述
看看PinYinUtil.java的代码是怎样的

package com.mengyuan.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音工具类,能将汉字转换成拼音的首字母
 */
public class PinYinUtil {
	// 名字长度
	private static int NAME_LENGTH = 3;

	/**
	 * 将首个汉字转换为全拼
	 * 其他是汉字首字母
	 * @param src
	 * @return
	 */
	public static String getPingYin(String src) {

		char[] name = src.toCharArray();
		String[] newName = new String[name.length];
		HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat();
		pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
		String account = "";
		int length = name.length;
		try {
			// 名字大于等于3个字的时候,姓取全称,名取首字母。
			if(length>=NAME_LENGTH){
				for (int i = 0; i < length; i++) {
					// 截取姓
					if(i==0){
						// 判断是否为汉字字符
						if (Character.toString(name[i]).matches("[\\u4E00-\\u9FA5]+")) {
							newName = PinyinHelper.toHanyuPinyinStringArray(name[i], pyFormat);
							account += newName[0];
						} else
							account += Character.toString(name[i]);
					}else{
						account += getPinYinHeadChar(Character.toString(name[i]));
					}

				}
			}else{
				//只有2个字的名字,账号是名字的拼音全称
				for (int i = 0; i < length; i++) {
					// 判断是否为汉字字符
					if (Character.toString(name[i]).matches("[\\u4E00-\\u9FA5]+")) {
						newName = PinyinHelper.toHanyuPinyinStringArray(name[i], pyFormat);
						account += newName[0];
					} else
						account += Character.toString(name[i]);
				}
			}
			return account;
		} catch (BadHanyuPinyinOutputFormatCombination e1) {
			e1.printStackTrace();
		}
		return account;
	}

	/**
	 * 全部汉字转换成拼音
	 * @param src
	 * @return
	 */
	public static String getAllPingYin(String src) {
		StringBuffer sb = new StringBuffer();
		String [] arr = src.split("");
		for (String s : arr) {
			sb.append(PinYinUtil.getPingYin(s));
		}
		return sb.toString();
	}

	/**
	 * 返回中文的首字母
	 * @param str
	 * @return
	 */
	public static String getPinYinHeadChar(String str) {

		String convert = "";
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert += pinyinArray[0].charAt(0);
			} else {
				convert += word;
			}
		}
		return convert;
	}

	public static void main(String[] args) {
		String cn = "保存并插入数据库";
		System.out.println(PinYinUtil.getAllPingYin(cn));
		System.out.println(PinYinUtil.getPingYin(cn));
		System.out.println(PinYinUtil.getPinYinHeadChar(cn));
	}
}

这里面一共有三个方法,它们的区别是:
在这里插入图片描述
怎么实现这个拼音呢?
我们得到的拼音是书籍名字,则在增加的方法里添加这行代码
在这里插入图片描述
而它对应的是工具类里全拼方法
在这里插入图片描述
修改也需要这行代码,把这行代码也放进修改方法里
book.setPinyin(PinYinUtil.getAllPingYin(book.getName()));

二、Dao方法

这方法不需要讲了,直接发代码了,添加的三个方法而已

package com.mengyuan.dao;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.mengyuan.entity.Book;
import com.mengyuan.util.BaseDao;
import com.mengyuan.util.PageBean;
import com.mengyuan.util.PinYinUtil;
import com.mengyuan.util.StringUtils;

public class BookDao extends BaseDao<Book> {
	
	public List<Book> list(Book book,PageBean pageBean) throws Exception{
		String name=book.getName();
		String sql="select * from t_easyui_book where true";
		if(StringUtils.isNotBlank(name)) {
			sql+=" and name like '%"+name+"%'";
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}
//	//增加
	public int add(Book book) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
//		pinyin的属性值不少从jsp传递过来的
		book.setPinyin(PinYinUtil.getAllPingYin(book.getName()));
//		从前端jsp传到后端的deployTime属性值是string类型的,而数据库需要的是date/Timestamp
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String sql="insert into t_easyui_book values(null,?,?,?,?,?,?,?,?,?,?,?)";
		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"});
	}
public static void main(String[] args) throws Exception{
	BookDao bookDao=new BookDao();
	Book book=new Book();
	book.setName("种子");
	List<Book> list=bookDao.list(book, null);
	for (Book b : list) {
		System.out.println(b);
	}
}
}

三、Web层

我们在增删改的时候需要用到一个弹出的框来接收,这里就需要用到 dialog(对话框) ,点击增加弹出对话框。

通过已存在的DOM节点元素标签创建,下面的例子显示了可变大小的模式窗口。
在这里插入图片描述
将这段代码拷贝到增加页面里
不过现在是打开的,我们需要把它关闭,这里就用到了closed,在属性里添加关闭属性。
在这里插入图片描述
但是我们需要的是只有在点击增加的时候才弹出对话框,通过它们的id添加事件

//	给新增按钮绑定点击事件
	$("#btn-add").click(function(){
//		需要打开dialog窗体,查看该组件的方法api
		$('#bookEdit').dialog('open');
	})
	

开始写增加框里的东西
增加界面addbook.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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">   
<!-- 组件库源码 -->
<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" name="name"  id="name"  style="with:20%;padding-left:10px" data-options="label:'书名:'," >
	<a id="btn-search" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-serch',plain:true">搜索</a>
	<a id="btn-add" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-help',plain:true">新增</a> 
</div>
<div id="bookEdit" 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">   
    <div>   
        <label for="name">书籍名:</label>   
        <input class="easyui-validatebox" type="text" name="name" data-options="required:true" />   
    </div>
    <br/>   
    <div>   
        <label for="cid">书籍类别:</label>   
        <input class="easyui-validatebox" type="text" name="cid" data-options="validType:'email'" />   
    </div>  
    <br/>  
    <div>   
        <label for="price">书籍价格:</label>   
        <input class="easyui-validatebox" type="text" name="price" data-options="required:true" />   
    </div>   
    <br/> 
    <div>   
        <label for="author">作者:</label>   
        <input class="easyui-validatebox" type="text" name="author" data-options="validType:'email'" />   
    </div>   
    <div>   
        <label for="price">价格:</label>   
        <input class="easyui-validatebox" type="text" name="price" data-options="required:true" />   
    </div>   
    <br/> 
    <div>   
        <label for="image">图片地址:</label>   
        <input class="easyui-validatebox" type="text" name="image" data-options="validType:'email'" />   
    </div> 
    <br/> 
    <div>   
        <label for="publishing">出版社:</label>   
        <input class="easyui-validatebox" type="text" name="publishing" data-options="validType:'email'" />   
    </div>   
    <br/> 
    <div>   
        <label for="description">描述:</label>   
        <input class="easyui-validatebox" type="text" name="description" data-options="required:true" />   
    </div> 
    <br/>   
    <div>   
        <label for="state">物流状态:</label>   
        <input class="easyui-validatebox" type="text" name="state" data-options="validType:'email'" />   
    </div>  
    <div>   
        <label for="deployTime">发布时间:</label>   
        <input class="easyui-validatebox" type="text" name="deployTime" data-options="required:true" />   
    </div>  
    <br/>  
    <div>   
        <label for="sales">数量:</label>   
        <input class="easyui-validatebox" type="text" name="sales" data-options="validType:'email'" />   
    </div>  
</form>  

    
</div>  
<div id="fbtns">
	<a id="btn-save" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-serch',plain:true">保存</a>
	<a id="btn-canel" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-help',plain:true">取消</a> 
</div>

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

book.js 添加事件
在这里插入图片描述

为增删改添加一个辅助类

package com.mengyuan.util;
/**
 * (响应结果集)
 * @author 梦园
 *
 * 
 */
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) {
		super();
		this.code = code;
		this.msg = msg;
	}
	private Result() {
		super();
	}
	private Result(T data) {
		super();
		this.data = data;
	}
}

addAction.java

package com.mengyuan.web;


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.mengyuan.dao.BookDao;
import com.mengyuan.entity.Book;
import com.mengyuan.util.DataGridResult;
import com.mengyuan.util.PageBean;
import com.mengyuan.util.ResponseUtil;
import com.mengyuan.util.Result;
import com.sun.net.httpserver.Authenticator.Success;
import com.xiaoqing.frameWork.ActionSupport;
import com.xiaoqing.frameWork.ModelDriver;

public class BookAction extends ActionSupport implements ModelDriver<Book> {
	private Book book=new Book();
	private BookDao bookDao=new BookDao();
	@Override
	public Book getModel() {
		return book;
	}
	public String datagrid(HttpServletRequest req,HttpServletResponse resp) {
//		total中的数据从哪里来 ---》pagebean total属性
//		row的数据从哪里来---》每页的展示数据
		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
		try {
			List<Book> list = this.bookDao.list(book, pageBean);
//			Map<String, Object> map=new HashMap<String, Object>();
//			map.put("total", pageBean.getTotal());
//			map.put("rows", list);
//			硬代码
			ResponseUtil.writeJson(resp, DataGridResult.ok(pageBean.getTotal()+"",list));
//			ResponseUtil.writeJson(resp,DataGridResult.SUCCESS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	//增加
		public String add(HttpServletRequest req,HttpServletResponse resp) {
			try {
				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();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
//			ResponseUtil.writeJson(resp,Result.SUCCESS);
			
			return null;		
		}
		//修改
		public String edit(HttpServletRequest req,HttpServletResponse resp) {
				try {
					this.bookDao.edit(book);
//					new Result<>(200,"操作成功");
//					{code:200,msg:}
					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();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;		
			}
//		二合一   将新增/修改方法合成一个
		public String save(HttpServletRequest req,HttpServletResponse resp) {
			try {
				if(book.getId() != 0) {
					this.bookDao.edit(book);
				}else {
					this.bookDao.add(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();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;		
		}
		
		//删除
		public String del(HttpServletRequest req,HttpServletResponse resp) {
			try {
				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();
			} catch (Exception e) {
				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("total", asList);
		ObjectMapper om=new ObjectMapper();
		String jsonstr=om.writeValueAsString(map);
		System.out.println(jsonstr);
	}
}

在表内添加一个列字段(操作)在操作内添加弹出修改与删除,这个事件则添加到在这里插入图片描述

book.js全部事件

$(function(){
	var ctx=$("#ctx").val();
	$('#dg').datagrid({    
	    url:ctx+'/book.action?methodName=datagrid',    
	    pagination:true,
	    toolbar: '#tb',
	    columns:[[    
	        {field:'id',title:'id',width:100},    
	        {field:'name',title:'书籍名称',width:100},  
	        {field:'pinyin',title:'拼音',width:100,align:'right'},    
	        {field:'cid',title:'书籍类别',width:100}, 
	        {field:'author',title:'作者',width:100}, 
	        {field:'price',title:'书籍价格',width:100}, 
	        {field:'image',title:'图片',width:100}, 
	        {field:'publishing',title:'出版',width:100},
	        {field:'description',title:'描述',width:100},
	        {field:'state',title:'state',width:100},
	        {field:'deployTime',title:'上架时间',width:100},
	        {field:'sales',title:'销量',width:100},
	        {field:'xxx',title:'操作',width:300,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(11);
		$('#dg').datagrid('load', {    
		    name: $("#name").val()   
		});  
	});
//	给新增按钮绑定点击事件
	$("#btn-add").click(function(){
//		需要打开dialog窗体,查看该组件的方法api
		$('#bookEdit').dialog('open');
	});
	
	$("#btn-save").click(function(){
		 
		 $('#ff').form('submit', {    
			    url:ctx+'/book.action?methodName=save', 
			    onSubmit: function(){    
			       console.log('onSubmit..........');  
			    },    
			    success:function(data){    
			       data = eval('('+data+')'); 
			       if(data.code == 200){
			    	   alert(data.msg);
//			    	   刷新datagrid中的数据
			    	   $('#ff').form('clear');
			    	   $('#bookEdit').dialog('close');
			    	   $('#dg').datagrid('reload');
			       }
			    }    
			});  
	 });
		  
})
function edit(){
//	 做数据回显,就是将选中的datagrid行值回填到form表单
	 var row = $('#dg').datagrid('getSelected');
	 if(row){
		 $('#ff').form('load',row); 
	 }
//	 让用户看到form表单
	 $('#bookEdit').dialog('open');
 }
 
function del(){
	 var row = $('#dg').datagrid('getSelected');
	 if(row){
		 $.ajax({
			 url:ctx+'/book.action?methodName=del&&id='+row.id, 
			 success:function(data){    
			       data = eval('('+data+')'); 
			       if(data.code == 200){
			    	   alert(data.msg);
			    	   $('#dg').datagrid('reload');
			       }
			    }   
		 });
	 }
 }

添加信息的时间必须是自己设置的那个形式否则会报错
在这里插入图片描述
如果格式错了则会报这个错误
在这里插入图片描述
最终结果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_47906421/article/details/107007390