首页 > 代码库 > java整合easyui进行的增删改操作
java整合easyui进行的增删改操作
首先发一下效果图
显示所有用户信息
添加用户信息
删除用户信息
编辑用户信息
下面就来介绍一下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进行的增删改操作