首先发一下效果图

显示全部用户信息

加入用户信息

删除用户信息

编辑用户信息

以下就来介绍一下easyui的crud,在java中是怎么与后台进行交换的

前台html页面,我将它命名为crud1.html

1.首先是一个datagrid,通过class来标记。

关于url 直接给出官方的解释: To load data from remote server, you should set 'url' peoperty, where server will return JSON format data

其次是pagination(分页),它的官方解释是

set 'pagination' property to true, which will generate a pagination bar on datagrid bottom. The pagination will send two parameters to server:

  • page: The page number, start with 1.
  • rows: The page rows per page.

接着关于thread官方的解释是 datagrid columns is defined in <thead> markup(datagrid的列是定义在<thread>标记之中的)

2.工具栏

关于工具栏,We don't need to write any javascript code, attach a toolbar to the datagrid via 'toolbar' attribute.

工具栏中通过定义时所写的onclick方法来完毕调用。

3.工具栏中定义的方法

方法位于js中,举例。如:newUser这种方法

点击"加入用户"这个工具栏,就会调用js中的newUser()方法

(1)打开 id为dlg的对话框,而且对话框的标题设置为 "加入用户"

$("#dlg").dialog('open').dialog('setTitle','加入用户');

(2)对话框的定义。在body之中是这样定义的,此处不多解释

<div id="dlg" class="easyui-dialog" style="width:400px;height:250px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<form id="fm" method="post">
<table cellspacing="10px;">
<tr>
<td>姓名:</td>
<td><input name="name" class="easyui-validatebox" required="true" style="width: 200px;"></td>
</tr>
<tr>
<td>联系电话:</td>
<td><input name="phone" class="easyui-validatebox" required="true" style="width: 200px;"></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="email" class="easyui-validatebox" validType="email" required="true" style="width: 200px;"></td>
</tr>
<tr>
<td>QQ:</td>
<td><input name="qq" class="easyui-validatebox" required="true" style="width: 200px;"></td>
</tr>
</table>
</form>
</div> <div id="dlg-buttons">
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
</div>

(3)清除对话框的内容

$('#fm').form('clear');

(4)通过ajax与后台java程序进行交互

url='userSave';

后台的java程序是这种

接受用户传进来的四个值。完毕数据库的相关操作,然后将result的返回值,放到一个jsonObject之中

public class UserSaveServlet extends HttpServlet{

	/**
*
*/
private static final long serialVersionUID = 1L;
DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao(); @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name=request.getParameter("name");
String phone=request.getParameter("phone");
String email=request.getParameter("email");
String qq=request.getParameter("qq");
String id=request.getParameter("id"); User user=new User(name, phone, email, qq);
if(StringUtil.isNotEmpty(id)){
user.setId(Integer.parseInt(id));
} Connection con=null;
try {
int saveNums=0;
con=dbUtil.getCon();
JSONObject result=new JSONObject();
if(StringUtil.isNotEmpty(id)){
saveNums=userDao.userModify(con, user);
}else{
saveNums=userDao.userAdd(con, user);
}
if(saveNums==1){
result.put("success", "true");
}else{
result.put("success", "true");
result.put("errorMsg", "保存成功");
}
ResponseUtil.write(response, result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

好,以上就是完整的easyui和后台java程序的交互过程。

以下贴出完整代码:

项目结构:

数据库建表语句:就是一个t_user表

/*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.1.49-community : Database - db_easyui
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_easyui` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `db_easyui`; /*Table structure for table `t_user` */ DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
`qq` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; /*Data for the table `t_user` */

前台页面 crud1.html

<html>
<head>
<meta charset="UTF-8">
<title>Basic DataGrid - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/icon.css">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/demo/demo.css">
<script type="text/javascript" src="jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
<script>
var url;
function deleteUser(){
var row=$('#dg').datagrid('getSelected');
if(row){
$.messager.confirm("系统提示","您确定要删除这条记录吗? ",function(r){
if(r){
$.post('userDelete',{delId:row.id},function(result){
if(result.success){
$.messager.alert("系统提示","已成功删除这条记录!");
$("#dg").datagrid("reload");
}else{
$.messager.alert("系统提示",result.errorMsg);
}
},'json');
}
});
}
} function newUser(){
$("#dlg").dialog('open').dialog('setTitle','加入用户');
$('#fm').form('clear');
url='userSave';
} function editUser(){
var row=$('#dg').datagrid('getSelected');
if(row){
$("#dlg").dialog('open').dialog('setTitle','编辑用户');
$('#fm').form('load',row);
url='userSave?id='+row.id;
}
} function saveUser(){
$('#fm').form('submit',{
url:url,
onSubmit:function(){
return $(this).form('validate');
},
success:function(result){
var result=eval('('+result+')');
if(result.errorMsg){
$.messager.alert("系统提示",result.errorMsg);
return;
}else{
$.messager.alert("系统提示","保存成功");
$('#dlg').dialog('close');
$("#dg").datagrid("reload");
}
}
});
} </script>
</head>
<body>
<table id="dg" title="用户管理" class="easyui-datagrid" style="width:700px;height:365px"
url="userList"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="id" width="50" hidden="true">编号</th>
<th field="name" width="50">姓名</th>
<th field="phone" width="50">电话</th>
<th field="email" width="50">Email</th>
<th field="qq" width="50">QQ</th>
</tr>
</thead>
</table>
<div id="toolbar">
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">加入用户</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">编辑用户</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="deleteUser()">删除用户</a>
</div> <div id="dlg" class="easyui-dialog" style="width:400px;height:250px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<form id="fm" method="post">
<table cellspacing="10px;">
<tr>
<td>姓名:</td>
<td><input name="name" class="easyui-validatebox" required="true" style="width: 200px;"></td>
</tr>
<tr>
<td>联系电话:</td>
<td><input name="phone" class="easyui-validatebox" required="true" style="width: 200px;"></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="email" class="easyui-validatebox" validType="email" required="true" style="width: 200px;"></td>
</tr>
<tr>
<td>QQ:</td>
<td><input name="qq" class="easyui-validatebox" required="true" style="width: 200px;"></td>
</tr>
</table>
</form>
</div> <div id="dlg-buttons">
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
</div>
</body>

model层对user表和pageBean的封装

public class PageBean {

	private int page; // 第几页
private int rows; // 每页的记录数
private int start; // 起始页
//省略get和set方法
}
public class User {

	private int id;
private String name;
private String phone;
private String email;
private String qq; public User() {
} public User(String name, String phone, String email, String qq) {
this.name = name;
this.phone = phone;
this.email = email;
this.qq = qq;
}
//省略get和set方法
}

工具类:

(1)连接数据库的类

public class DbUtil {

	private String dbUrl="jdbc:mysql://localhost:3306/db_easyui";
private String dbUserName="root";
private String dbPassword="root";
private String jdbcName="com.mysql.jdbc.Driver"; public Connection getCon()throws Exception{
Class.forName(jdbcName);
Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
return con;
} public void closeCon(Connection con)throws Exception{
if(con!=null){
con.close();
}
}
}
(2)将result转换成json数组的工具类
public class JsonUtil { /**
* 将result的结果集转化成json数组格式
* @param rs
* @return
* @throws Exception
*/
public static JSONArray formatRsToJsonArray(ResultSet rs)throws Exception{
ResultSetMetaData md=rs.getMetaData();
int num=md.getColumnCount();
JSONArray array=new JSONArray();
while(rs.next()){
JSONObject mapOfColValues=new JSONObject();
for(int i=1;i<=num;i++){
mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
}
array.add(mapOfColValues);
}
return array;
}
}

(3)向页面输出信息的类

public class ResponseUtil {

	public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.print(o.toString());
out.flush();
out.close();
}
}

以下是控制层controller

删除用户信息的controller

public class UserDeleteServlet extends HttpServlet{

	/**
*
*/
private static final long serialVersionUID = 1L;
DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao(); @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// String delId=request.getParameter("delId");
String delId=request.getParameter("delId");
Connection con=null;
try {
con=dbUtil.getCon();
JSONObject result=new JSONObject();
int delNums=userDao.userDelete(con, delId);
if(delNums==1){
result.put("success", "true");
}else{
result.put("errorMsg", "删除失败");
}
ResponseUtil.write(response, result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } }

显示用户信息的controller

public class UserListServlet extends HttpServlet{

	/**
*
*/
private static final long serialVersionUID = 1L;
DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao(); @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page=request.getParameter("page");
String rows=request.getParameter("rows");
PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows)); Connection con=null;
try {
con=dbUtil.getCon();
JSONObject result=new JSONObject();
JSONArray jsonArray=JsonUtil.formatRsToJsonArray(userDao.userList(con, pageBean));
int total=userDao.userCount(con);
result.put("rows", jsonArray);
result.put("total", total);
ResponseUtil.write(response, result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } }

保存用户信息的controller

public class UserSaveServlet extends HttpServlet{

	/**
*
*/
private static final long serialVersionUID = 1L;
DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao(); @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name=request.getParameter("name");
String phone=request.getParameter("phone");
String email=request.getParameter("email");
String qq=request.getParameter("qq");
String id=request.getParameter("id"); User user=new User(name, phone, email, qq);
if(StringUtil.isNotEmpty(id)){
user.setId(Integer.parseInt(id));
} Connection con=null;
try {
int saveNums=0;
con=dbUtil.getCon();
JSONObject result=new JSONObject();
if(StringUtil.isNotEmpty(id)){
saveNums=userDao.userModify(con, user);
}else{
saveNums=userDao.userAdd(con, user);
}
if(saveNums==1){
result.put("success", "true");
}else{
result.put("success", "true");
result.put("errorMsg", "保存成功");
}
ResponseUtil.write(response, result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

最后附上配置文件web.xml

<servlet>
<servlet-name>userListServlet</servlet-name>
<servlet-class>com.qzp.web.UserListServlet</servlet-class>
</servlet> <servlet>
<servlet-name>userDeleteServlet</servlet-name>
<servlet-class>com.qzp.web.UserDeleteServlet</servlet-class>
</servlet> <servlet>
<servlet-name>userSaveServlet</servlet-name>
<servlet-class>com.qzp.web.UserSaveServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>userListServlet</servlet-name>
<url-pattern>/userList</url-pattern>
</servlet-mapping> <servlet-mapping>
<servlet-name>userDeleteServlet</servlet-name>
<url-pattern>/userDelete</url-pattern>
</servlet-mapping> <servlet-mapping>
<servlet-name>userSaveServlet</servlet-name>
<url-pattern>/userSave</url-pattern>
</servlet-mapping>

java整合easyui进行的增删改操作的更多相关文章

  1. Jquery easyui开启行编辑模式增删改操作

    Jquery easyui开启行编辑模式增删改操作 Jquery easyui开启行编辑模式增删改操作先上图 Html代码: <table id="dd"> </ ...

  2. [转]Jquery easyui开启行编辑模式增删改操作

    本文转自:http://www.cnblogs.com/nyzhai/archive/2013/05/14/3077152.html Jquery easyui开启行编辑模式增删改操作先上图 Html ...

  3. java中集合的增删改操作及遍历总结

      集合的增删改操作及遍历总结

  4. OracleHelper(对增删改查分页查询操作进行了面向对象的封装,对批量增删改操作的事务封装)

    公司的一个新项目使用ASP.NET MVC开发,经理让我写个OracleHelper,我从网上找了一个比较全的OracleHelper类,缺点是查询的时候返回DataSet,数据增删改要写很多代码(当 ...

  5. 使用java对sql server进行增删改查

    import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import ...

  6. 详解连接SQL Server数据库的方法,并使用Statement接口实现对数据库的增删改操作

    总结一下,连接SQL Server数据库需要以下几个步骤: 1. 导入驱动Jar包:sqljdbc.jar 2. 加载并注册驱动程序 3. 设置连接路径 4. 加载并注册驱动 5. 连接数据库 6. ...

  7. Java API实现Hadoop文件系统增删改查

    Java API实现Hadoop文件系统增删改查 Hadoop文件系统可以通过shell命令hadoop fs -xx进行操作,同时也提供了Java编程接口 maven配置 <project x ...

  8. 使用PreparedStatement接口实现增删改操作

    直接上下代码: package com.learn.jdbc.chap04.sec02; import java.sql.Connection; import java.sql.PreparedSta ...

  9. EasyUI----DataGrid行明细增删改操作

    http://blog.csdn.net/huchiwei/article/details/7787947   本文实现的是EasyUI-DataGrid行明细的增删改操作.具体参考来自以下文章: 官 ...

随机推荐

  1. D-Separation(D分离)

    是属于 Bayesian network 中的概念

  2. LINUX下 Udev详解

    如果你使用Linux比较长时间了,那你就知道,在对待设备文件这块,Linux改变了几次策略.在Linux早期,设备文件仅仅是是一些带有适当的属性集的普通文件,它由mknod命令创建,文件存放在/dev ...

  3. 使用ASIHttoRequest需要导入的framework

    需要导入如下framework libxml2.2.dylib libz.1.2.5.dylib MobileCoreServices.framework SystemConfiguration.fr ...

  4. Android 4.4 Kitkat Phone工作流程浅析(六)__InCallActivity显示更新流程

    本文来自http://blog.csdn.net/yihongyuelan 转载请务必注明出处 本文代码以MTK平台Android 4.4为分析对象,与Google原生AOSP有些许差异,请读者知悉. ...

  5. ES6的模块化

    在之前的 javascript 中一直是没有模块系统的,前辈们为了解决这些问题,提出了各种规范, 最主要的有CommonJS和AMD两种.前者用于服务器,后者用于浏览器.而 ES6 中提供了简单的模块 ...

  6. 每日一发linux命令

    很多用虚拟机的同学在向/tmp目录下进行解压的时候,会发现之前挂载的此目录空间不足,导致下一步无法进行(我在vmwaretools解压的时候就遇到了这个problem)…… 实际上,/tmp是可以进行 ...

  7. Gridview 多重表头 (二)

    多重表头之排序 这是个有点忧桑的故事...Cynthia告诉我,研究一个问题,我们不可能有超过一天的时间... 结果好好几天过去鸟~~还没有完成... 由于不再使用Gridview自带的表头行,于是无 ...

  8. SQL Server 添加一条数据获取自动增长列的几种方法

      数据库表设计  邓老师(老邓教的) insert into TestOne ','Test011') select @@IDENTITY as '自动增长ID' 杨老师(老杨教的) insert ...

  9. android spinner 每行字体颜色都变化

    final static int[] COLOR_LIST={Color.WHITE,Color.WHITE,Color.GRAY,Color.YELLOW,Color.RED}; spinner=( ...

  10. oracle取分组的前N条数据

    select * from(select animal,age,id, row_number()over(partition by animal order by age desc) row_num ...