Easyui的datagrid(增删改)及form表单

datagrid(增删改)及form表单

  • datagrid(增删改)
    • 拼音的工具包和类
    • 增删改所需的辅助工具类
  • form表单
    • jsp界面代码
    • 界面js
  • 界面结果图

datagrid(增删改)

拼音的工具包和类

先导入拼音的工具包再导入工具类Easyui的datagrid(增删改)及form表单_第1张图片
PinYinUtil.java

package com.tang.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));
	}
}

增删改所需的辅助工具类

Result.java

package com.tang.util;
/**
 * (响应结果集)
 * @author Administrator
 *
 * @param <T>
 */
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;
	}
	

}

BookDao.java

package com.tang.dao;

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

import com.tang.entity.Book;
import com.tang.util.BaseDao;
import com.tang.util.PageBean;
import com.tang.util.PinYinUtil;
import com.tang.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 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"});
		}
	
}

BookAction.java

package com.tang.web;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.tang.dao.BookDao;
import com.tang.entity.Book;
import com.tang.util.DataGridRedult;
import com.tang.util.PageBean;
import com.tang.util.ResponseUtil;
import com.tang.util.Result;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriven;

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) {
		//total中的数据从哪来?---》pagebean total属性
		//rows的数据从哪来----》每页的展示数据
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		try {
			List<Book> list = this.bookDao.list(book, pageBean);
			ResponseUtil.writeJson(resp, DataGridRedult.ok(pageBean.getTotal()+"", list));
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
		return null;		
	}
	
	//增加
	public String add(HttpServletRequest req,HttpServletResponse resp) {
		try {
			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 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;		
	}
	

}

form表单

jsp界面代码

form表单是不需要去后台写界面,直接在前台弹出一个form表单

addBook.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>书籍新增界面</title>
</head>
<body>
 <input type="hidden" id="ctx" value="${pageContext.request.contextPath }"> 

	<div id="tb">
		 <input class="easyui-textbox" id="name" 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>
	
	<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">  
			<input type="hidden" name="id"/>    
		    <div>   
		        <label for="name">书籍名称:</label>   
		        <input class="easyui-validatebox" type="text" name="name" data-options="required:true" />   
		    </div>   
		    <div>   
		        <label for="cid">书籍类别:</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">
		 <input class="easyui-textbox" id="name" name="name" style="width: 20%;padding-left:1-px " data-options="label:'书名:',required:true">
		<a id="btn-save" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit'">保存</a>
		<a id="btn-cancel" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-help'">取消</a>
	</div>

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


</body>
</html>

界面js

book.js

 $(function(){
	 var ctx = $("#ctx").val();
	 $('#dg').datagrid({    
		    url:ctx+'/book.action?methodName=datagrid', 
//		    分页
		    pagination:true,
//		    只允许选中一行
		    singleSelect: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:'状态',width:100},    
		        {field:'deployTime',title:'上架时间',width:100},
		        {field:'sales',title:'销量',width:100},
		        {field:'xxx',title:'操作',width:300,formatter: function(value,row,index){
					return '修改  删除'
				}
}
		    ]]    
		});
	 
	 //点击搜索按钮完成按名字进行书籍查询
	 $("#btn-search").click(function(){
		 $('#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');
			       }
			    }   
		 });
	 }
 }


界面结果图

整体界面结果
Easyui的datagrid(增删改)及form表单_第2张图片
界面新增结果
Easyui的datagrid(增删改)及form表单_第3张图片

界面修改结果
Easyui的datagrid(增删改)及form表单_第4张图片

你可能感兴趣的:(Easyui的datagrid(增删改)及form表单)