一、前言
上次博客给大家分享了datagrid的查询这次给大家分享的是在上篇博客的基础上增加“增删改”
上篇博客链接:点击
二、easyui后端代码编写
dao方法
// 增加
public int add(Book b) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
// pingyin的属性值不是从jsp传剃过来的
b.setPinyin(PinYinUtil.getAllPingYin(b.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, b, new String[] {"name","pinyin","cid","author","price","image","publishing","description","state","deployTime","sales"});
}
// 修改
public int edit(Book b) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
b.setPinyin(PinYinUtil.getAllPingYin(b.getName()));
String sql="update t_easyui_book set name=?,pinyin=?,cid=?,author=?,price=?,image=?,publishing=?,description=?,state=?,deployTime=?,sales=?,id=?";
return super.executeUpdate(sql, b, new String[] {"name","pinyin","cid","author","price","image","publishing","description","state","deployTime","sales","id"});
}
// 删除
public int del(Book b) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
String sql="delete from t_easyui_book where id=?";
return super.executeUpdate(sql, b, new String[] {"id"});
}
注上面代码要加入一个拼音工具包和拼音工具类
工具类代码
package com.chendongyang.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));
}
}
拼音工具类获取链接: 添加链接描述
提取码: p6tj
2、bookAction
package com.chendongyang.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.chendongyang.dao.BookDao;
import com.chendongyang.entity.Book;
import com.chendongyang.framework.ActionSupport;
import com.chendongyang.framework.ModelDriven;
import com.chendongyang.util.DataGridResult;
import com.chendongyang.util.PageBean;
import com.chendongyang.util.ResponseUtil;
import com.chendongyang.util.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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 SQLException, Exception{
// total中的数据从哪来 pagebean中的属性
// rows的数据从哪来 没页条目数
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
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));
return null;
}
/*public static void main(String[] args) throws JsonProcessingException {
Map<String, Object> map=new HashMap<String, Object>();
map.put("total", 34);
List<Book> asList = Arrays.asList(new Book(1, "df", "df"),new Book(2, "dg", "dg"),new Book(3, "dh", "dh"));
map.put("rows", asList);
ObjectMapper om=new ObjectMapper();
String jsonstr =om.writeValueAsString(map);
System.out.println(jsonstr);
}*/
public String add(HttpServletRequest req,HttpServletResponse resp) throws Exception{
try {
int add = this.bookDao.add(book);
// {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();
}
return null;
}
public String edit(HttpServletRequest req,HttpServletResponse resp){
try {
this.bookDao.edit(book);
} 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 del(HttpServletRequest req,HttpServletResponse resp){
try {
this.bookDao.del(book);
try {
ResponseUtil.writeJson(resp, Result.SUCCESS);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} 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;
}
}
三、easyui的前端新增实现
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/default/easyui.css">
<script type="text/javascript"
src="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>
<!-- 组件库源码的js文件 -->
<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-taxtbox" id="name" style="width:20%;padding-left: 10px" data-options="label:'书名 :',required:true">
<a id="btn-search" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'">搜索</a>
<a id="btn-add" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'">新增</a>
</div>
<!-- 模态框窗口 -->
<div id="bookEdit" class="easyui-dialog" title="书籍信息编辑窗体" style="width:400px;height:350px;"
data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#fbtns'">
<!-- 书籍信息 -->
<form id="ff" method="post">
<input class="easyui-validatebox" type="text" name="id" />
<div>
<label for="name">书籍名称:</label>
<input type="hidden" 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">
<a id="btn-save" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'">保存</a>
<a id="btn-cancel" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'">取消</a>
</div>
<table id="dg"></table>
</body>
</html>
编写工具类:Result
package com.chendongyang.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;
}
public Result() {
super();
}
public Result(int code, String msg) {
this.msg = msg;
this.data = data;
}
public Result(int code, String msg, T data) {
super();
this.code = code;
this.msg = msg;
this.data = data;
}
public Result(T data) {
super();
this.data = data;
}
}
book.js界面修改
```cpp
$(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:'xxx',title:'操作',width:100,formatter: function(value,row,index){
return '<a href="javascript:void(0)" οnclick="edit()">修改</a> <a href="javascript:void(0)" οnclick="edit()">删除</a>'
}
}
]]
});
// 点击搜索按钮完成按名字进行书籍查询
$("#btn-search").click(function(){
// alert("cahd")
$('#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=add',
onSubmit: function(){
console.log('onSubmit...');
},
success:function(data){
data=eval('('+data+')');
if(data.code == 200){
alert(data.msg)
// 刷新datagrid的数据
$('#dg').datagrid('reload');
$('#ff').from('clear');
$('#bookEdit').dialog('close');
}
}
});
});
})
四、easyui增删改
book.js 里面最底下增加以下代码
function edit(){
// alert(1);
// 做数据回显,就是将选中的行值回填到form表单
//
var row=$('#dg').datagrid('getSelected');
if(row){
$('#ff').form('load',row);
}
// 让用户看到模态框
$('#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)
// 刷新datagrid的数据
$('#dg').datagrid('reload');
}
}
});
}
}
BookAction.jsp界面添加下面方法
// 二和一的方法 将新增或者修改合成一个
public String save(HttpServletRequest req,HttpServletResponse resp){
try {
if(book.getId() !=0) {
this.bookDao.edit(book);
}else {
this.bookDao.add(book);
}
try {
ResponseUtil.writeJson(resp, Result.SUCCESS);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} 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;
}