首先发一下效果图

显示全部用户信息

加入用户信息

删除用户信息

编辑用户信息

以下就来介绍一下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. AutoResetEvent与ManualResetEvent区别

    本文来自:http://www.360doc.com/content/10/1126/10/3267996_72536817.shtml 在.Net多线程编程中,AutoResetEvent和Manu ...

  2. Windows Server 2008 R2 开启Win7主题效果Aero

    1.打开 开始---管理工具----服务器管理器--功能 2.点击 “添加功能”,选择“桌面体验”,这样就会安装上win7 主题和Windows media player 3.重启电脑后,在“服务”里 ...

  3. 矩阵经典题目六:poj 3070 Fibonacci

    http://poj.org/problem?id=3070 按已构造好的矩阵,那么该矩阵的n次方的右上角的数便是f[n]. #include <stdio.h> #include < ...

  4. 如何统一删除word中的超链接

    [摘要] 我们从别处拷贝文字,或从网上复制的文字,里面有很多超级链接,如何可以批量删除这些链接呢?这里介绍两种批量删除链接的方法. [正文] 方法一:使用快捷键删除超链接 有个神奇的快捷键,可以帮我们 ...

  5. Java String类具体解释

    Java String类具体解释 Java字符串类(java.lang.String)是Java中使用最多的类,也是最为特殊的一个类,非常多时候,我们对它既熟悉又陌生. 类结构: public fin ...

  6. VS2013报表设计常用表达式

    一.页眉 1."日期"表达式:="日期: "& Today.ToShortDateString() 效果: 2.格式化日期:="日期: &qu ...

  7. WPF实现窗体最小化后小图标在右边任务栏下

    一 基本功能 1. 这里是用 NotifyIcon 控件来实现,但 WPF 下没有 NotifyIcon  控件,怎么办,用 WinForm 下的呗. 先引用  .NET 自带的两个程序集 Syste ...

  8. iOS 生成.a文件

    一.新建一个工程,选择Cocoa Touch Static Library. 二. 三. 四. 五. 六. 七. 八. 九. 十. 十一. 十二. 十三.打开终端,输入以下命令将真机和模拟器中的.a合 ...

  9. F - The Circumference of the Circle

    Description To calculate the circumference of a circle seems to be an easy task - provided you know ...

  10. mysql数据库数据恢复方案概括总结

    方案一:(传统方案) 备份+binlog日志增量: 方案二:(针对update.delete语句忘加where的情况) Binlog日志文件中保存有错误操作之前和之后的两组数据,将错误操作之前的数据修 ...