EasyUI--增删改查

easyui的crud

陈旧的开发模式
 美工(ui工程师:出一个项目模型)
 java工程师:将原有的html转成jsp,动态展示数据
 缺点:
  客户需要调节前端的展示效果
  解决:由美工去重新排版,重新选色。


前后端分离
 美工、java工程师都是独立工作的,彼此之间在开发过程中是没有任何交际。
 在开发前约定数据交互的格式。
 java工程师的工作:写方法返回数据如tree_data1.json
 美工:只管展示tree_data1.json

 

.主要用到的三个布局dialog,datagrid、form

1、通用的JsonBaseDao增删改方法

 

 1 package com.yuan.util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.sql.ResultSetMetaData;
 7 import java.sql.SQLException;
 8 import java.util.ArrayList;
 9 import java.util.HashMap;
10 import java.util.List;
11 import java.util.Map;
12 
13 public class JsonBaseDao extends BaseDao<Map<String,Object>> {
14     public List<Map<String,Object>> executeQuery(String sql, PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
15         return super.executeQuery(sql, pageBean, new Callback<Map<String,Object>>() {
16             @Override
17             public List<Map<String,Object>> foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException {
18                 /*
19                  * 1、创建一个实体类的实例
20                  * 2、给创建的实例属性赋值
21                  * 3、将添加完类容的实体类添加到list集合中
22                  */
23 //                list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
24                 List<Map<String,Object>> list = new ArrayList<>();
25 //                获取数据源
26                 ResultSetMetaData md = rs.getMetaData();
27                 int count = md.getColumnCount();
28                 Map<String,Object> map = null;
29                 while(rs.next()) {
30                     map = new HashMap<>();
31                     for (int i = 1; i <= count; i++) {
32                         map.put(md.getColumnName(i), rs.getObject(i));
33                     }
34                     list.add(map);
35                 }
36                 return list;
37             }
38         });
39     }
40     
41     /**
42      * 
43      * @param sql
44      * @param attrs    map中的key
45      * @param paMap    jsp向后台传递的参数集合
46      * @return
47      * @throws SQLException
48      * @throws NoSuchFieldException
49      * @throws SecurityException
50      * @throws IllegalArgumentException
51      * @throws IllegalAccessException
52      */
53     public int executeUpdate(String sql, String[] attrs, Map<String,String[]> paMap) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
54         Connection con = DBAccess.getConnection();
55         PreparedStatement pst = con.prepareStatement(sql);
56         for (int i = 0; i < attrs.length; i++) {
57             pst.setObject(i+1, JsonUtils.getParamVal(paMap, attrs[i]));
58         }
59         return pst.executeUpdate();
60     }
61 }

 

 

2、dao层

 

  1 package com.yuan.dao;
  2 
  3 import java.sql.SQLException;
  4 import java.util.List;
  5 import java.util.Map;
  6 
  7 import com.yuan.util.JsonBaseDao;
  8 import com.yuan.util.JsonUtils;
  9 import com.yuan.util.PageBean;
 10 import com.yuan.util.StringUtils;
 11 
 12 public class UserDao extends JsonBaseDao {
 13 
 14     /**
 15      * 用户登录或者查询用户分页信息的公共方法
 16      * @param paMap
 17      * @param pageBean
 18      * @return
 19      * @throws InstantiationException
 20      * @throws IllegalAccessException
 21      * @throws SQLException
 22      */
 23     public List<Map<String, Object>> list(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
 24         String sql="SELECT * FROM t_easyui_user_version2 WHERE TRUE ";
 25         String uid=JsonUtils.getParamVal(paMap, "uid");
 26         String upwd=JsonUtils.getParamVal(paMap, "upwd");
 27         if(StringUtils.isNotBlank(uid)) {
 28             sql +=" AND uid="+uid;
 29         }
 30         if(StringUtils.isNotBlank(upwd)) {
 31             sql +=" AND upwd="+upwd;
 32         }
 33         return super.executeQuery(sql, pageBean);
 34     }
 35     
 36     /**
 37      * 新增
 38      * @param paMap
 39      * @return
 40      * @throws NoSuchFieldException
 41      * @throws SecurityException
 42      * @throws IllegalArgumentException
 43      * @throws IllegalAccessException
 44      * @throws SQLException
 45      */
 46     public int add(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
 47         String sql="insert into t_easyui_user_version2 values(?,?,?,?) ";
 48         System.out.println(sql);
 49         return super.executeUpdate(sql, new String[] {"SerialNo","uid","uname","upwd"}, paMap);
 50     }
 51     
 52     
 53     /**
 54      * 修改
 55      * @param paMap
 56      * @return
 57      * @throws NoSuchFieldException
 58      * @throws SecurityException
 59      * @throws IllegalArgumentException
 60      * @throws IllegalAccessException
 61      * @throws SQLException
 62      */
 63     public int edit(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
 64         String sql="update t_easyui_user_version2 set uid=?,uname=?,upwd=? where serialno=?";
 65         System.out.println(sql);
 66         return super.executeUpdate(sql, new String[] {"uid","uname","upwd","SerialNo"}, paMap);
 67     }
 68     
 69     /**
 70      * 删除
 71      * @param paMap
 72      * @return
 73      * @throws NoSuchFieldException
 74      * @throws SecurityException
 75      * @throws IllegalArgumentException
 76      * @throws IllegalAccessException
 77      * @throws SQLException
 78      */
 79     public int remove(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
 80         String sql = "delete from t_easyui_user_version2 where SerialNo=?";
 81         System.out.println(sql);
 82         return super.executeUpdate(sql, new String[] {"SerialNo"}, paMap);
 83         
 84     }
 85     
 86     
 87     /**
 88      * 根据当前用户登录的ID去查询对应的所有菜单
 89      * @param paMap
 90      * @param pageBean
 91      * @return
 92      * @throws InstantiationException
 93      * @throws IllegalAccessException
 94      * @throws SQLException
 95      */
 96     public List<Map<String, Object>> getMenuByUid(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
 97         String sql="SELECT * FROM t_easyui_usermenu WHERE TRUE ";
 98         String uid=JsonUtils.getParamVal(paMap, "uid");
 99         if(StringUtils.isNotBlank(uid)) {
100             sql +=" AND uid="+uid;
101         }
102         return super.executeQuery(sql, pageBean);
103     }
104     
105     
106 }

 

 

3、web层

 

  1 package com.yuan.web;
  2 
  3 import java.sql.SQLException;
  4 import java.util.HashMap;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 
 11 import org.apache.catalina.util.RequestUtil;
 12 
 13 import com.fasterxml.jackson.core.JsonProcessingException;
 14 import com.fasterxml.jackson.databind.ObjectMapper;
 15 import com.yuan.dao.UserDao;
 16 import com.yuan.util.PageBean;
 17 import com.yuan.util.ResponseUtil;
 18 import com.***.framework.ActionSupport;
 19 
 20 public class UserAction extends ActionSupport {
 21     
 22     private UserDao userDao = new UserDao();
 23     /**
 24      * 登录成功后跳转index.jsp
 25      * @param request
 26      * @param response
 27      * @return
 28      */
 29     public String login(HttpServletRequest request,HttpServletResponse response) {
 30 //        系统中是否有当前登录用户
 31         Map<String, Object> map = null;
 32         try {
 33             map = this.userDao.list(request.getParameterMap(), null).get(0);
 34         } catch (Exception e) {
 35             request.setAttribute("msg", "用户不存在");
 36             return "login";
 37         }
 38         try {
 39             //有就查询用户菜单中间表,获取对应menuid的集合
 40             if(map!=null&&map.size()>0) {
 41                 //得到[{Menuid:002,...},{Menuid:003,...}]
 42                 //截成002,003
 43                 StringBuilder sb= new StringBuilder();
 44                 List<Map<String, Object>> menuByUid = this.userDao.getMenuByUid(request.getParameterMap(), null);
 45                 for (Map<String, Object> m : menuByUid) {
 46                     sb.append(","+m.get("menuId"));
 47                 }
 48                 request.setAttribute("menuIds", sb.substring(1));
 49                  return "index";
 50             }else {
 51                 //没有就重新跳回登陆界面,并提示用户不存在
 52                 request.setAttribute("msg", "用户不存在");
 53                  return "login";
 54             }
 55         } catch (InstantiationException | IllegalAccessException | SQLException e) {
 56             // TODO Auto-generated catch block
 57             e.printStackTrace();
 58              return "login";
 59         }
 60         
 61     }     
 62     
 63     /**
 64      * 数据表格加载方法
 65      * @param request
 66      * @param response
 67      * @return
 68      */
 69     public String list(HttpServletRequest request,HttpServletResponse response) {
 70         ObjectMapper om= new ObjectMapper();
 71         PageBean pageBean = new PageBean();
 72         pageBean.setRequest(request);
 73         try {
 74             List<Map<String, Object>> list = this.userDao.list(request.getParameterMap(), pageBean);
 75             Map<String, Object> map = new HashMap<String, Object>();
 76             map.put("total", pageBean.getTotal());
 77             map.put("rows", list);
 78             ResponseUtil.write(response,om.writeValueAsString(map));
 79         } catch (Exception e) {
 80             // TODO Auto-generated catch block
 81             e.printStackTrace();
 82         }
 83         return null;
 84         
 85     }     
 86     
 87     /**
 88      * form组建提交方法
 89      * @param request
 90      * @param response
 91      * @return
 92      */
 93     public String edit(HttpServletRequest request,HttpServletResponse response) {
 94         try {
 95             int code=this.userDao.edit(request.getParameterMap());
 96             ObjectMapper om = new ObjectMapper();
 97             Map<String, Object> map = new HashMap<String, Object>();
 98             map.put("code", code);
 99             ResponseUtil.write(response, om.writeValueAsString(map));
100         } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
101                 | SQLException e) {
102             // TODO Auto-generated catch block
103             e.printStackTrace();
104         } catch (JsonProcessingException e) {
105             // TODO Auto-generated catch block
106             e.printStackTrace();
107         } catch (Exception e) {
108             // TODO Auto-generated catch block
109             e.printStackTrace();
110         }
111         return null;
112         
113     }     
114     
115     /**
116      * 新增
117      * @param req
118      * @param resp
119      * @return
120      * @throws InstantiationException
121      * @throws IllegalAccessException
122      * @throws SQLException
123      * @throws Exception
124      */
125     public String add(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException, Exception {
126         int code=this.userDao.add(req.getParameterMap());
127         ObjectMapper om = new ObjectMapper();
128         Map<String, Object> map = new HashMap<>();
129         map.put("code", code);
130         ResponseUtil.write(resp, om.writeValueAsString(map));
131         return null;
132     }
133     
134     /**
135      * 删除
136      * @param req
137      * @param resp
138      * @return
139      * @throws InstantiationException
140      * @throws IllegalAccessException
141      * @throws SQLException
142      * @throws Exception
143      */
144     public String remove(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException, Exception {
145         int code=this.userDao.remove(req.getParameterMap());
146         ObjectMapper om = new ObjectMapper();
147         Map<String, Object> map = new HashMap<>();
148         map.put("code", code);
149         ResponseUtil.write(resp, om.writeValueAsString(map));
150         return null;
151     }
152     
153     
154     
155 }

 

 

4、jsp页面代码

 

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>人员信息维护管理界面</title>
 8 <!-- Ctrl+Shift+r -->
 9 <link rel="stylesheet" type="text/css"
10     href="${pageContext.request.contextPath}/static/js/public/easyui5/themes/default/easyui.css">
11 <link rel="stylesheet" type="text/css"
12     href="${pageContext.request.contextPath}/static/js/public/easyui5/themes/icon.css">
13 <script type="text/javascript"
14     src="${pageContext.request.contextPath}/static/js/public/easyui5/jquery.min.js"></script>
15 <script type="text/javascript"
16     src="${pageContext.request.contextPath}/static/js/public/easyui5/jquery.easyui.min.js"></script>
17 <script type="text/javascript"
18     src="${pageContext.request.contextPath}/static/js/userManage.js"></script>
19 
20 </head>
21 <body>
22     <!-- 展示数据 -->
23     <table id="dg"></table>
24     <!-- 对话弹窗 -->
25     <div id="dd" class="easyui-dialog" title="编辑窗体"
26         style="width: 400px; height: 200px;"
27         data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#bb'">
28         <!-- 提交的from表单 -->
29         <form id="ff" method="post">
30             <input type="hidden" name="SerialNo">
31             <input type="hidden" id="method">
32             
33             <!-- 
34    
35      easyui自带正则:
36      但是如果你想要正则规则在easyui中不存在,easyui中只是定义了一些常见的正则表达式
37      那么可以在easyui中自定义正则(validType:'xxx')
38 
39  -->
40 
41             <div>
42                 <label for="uid">uid:</label> <input class="easyui-validatebox"
43                     type="text" name="uid" data-options="required:true" />
44             </div>
45             <div>
46                 <label for="uname">uname:</label> <input class="easyui-validatebox"
47                     type="text" name="uname" data-options="required:true" />
48             </div>
49             <div>
50                 <label for="upwd">upwd:</label> <input class="easyui-validatebox"
51                     type="text" name="upwd" data-options="required:true" />
52             </div>
53         </form>
54     </div>
55     
56     <div id="bb">
57        <a href="#" class="easyui-linkbutton" onclick="ok()">保存</a>
58        <a href="#" class="easyui-linkbutton">关闭</a>
59     </div>
60 
61 
62 </body>
63 </html>

 

 

 

 

5、功能完善

userManage.js代码

 1 $(function() {
 2     $('#dg').datagrid({
 3         url : '../userAction.action?methodName=list',
 4         fit : true,
 5         fitColumns : true,
 6         pagination : true,
 7         singleSelect : true,
 8         columns : [ [ {
 9             field : 'uid',
10             title : 'ID',
11             width : 100
12         }, {
13             field : 'uname',
14             title : '用户名',
15             width : 100
16         }, {
17             field : 'upwd',
18             title : '密码',
19             width : 100,
20             align : 'right'
21         } ] ],
22         toolbar : [ {
23             //新增按钮
24             iconCls : 'icon-add',
25             handler : function() {
26                 alert('新增按钮');
27                 $('#ff').form('clear');
28                 $('#dd').dialog('open');
29                 $('#method').val('add');
30                 $('#dg').datagrid('reload');
31 
32             }
33         }, '-', {
34             //修改按钮
35             iconCls : 'icon-edit',
36             handler : function() {
37                 alert('修改按钮');
38                 $("#dd").dialog('open')
39                 // 到datagrid控件中找需要回填的数据(区别于原来从后台查询)
40                 var row = $('#dg').datagrid('getSelected');
41                 if (row) {
42                     // 回显数据
43                     $("#ff").form('load', row);
44                 }
45             }
46         }, '-', {
47             //删除按钮
48             iconCls : 'icon-remove',
49             handler : function() {
50                 alert('移除按钮');
51                 var row =$('#dg').datagrid('getSelected');//选择你要删除的行
52                    if(row){//是否选中
53                     $.ajax({  
54 
55                     url:'../userAction.action?methodName=remove&&SerialNo='+row.SerialNo  
56                        });   
57                     alert('删除成功');
58                     $('#dg').datagrid('reload');//刷新
59                    }else{
60                     alert('删除失败');
61                    }
62             }
63         } ]
64     });
65 })
66    //提交按钮js代码
67 function ok(){
68 //    alert("ok");
69     $('#ff').form('submit', {    
70         url:'../userAction.action?methodName='+$("#method").val(),    
71         success:function(data){
72             $("#ff").form('clear');
73             $("#dd").dialog('close');
74             $("#dg").datagrid('reload');
75 //            alert(data)   
76            }    
78     });  
79 
80 }

6、运行结果

   6.1新增

EasyUI--增删改查EasyUI--增删改查

 

   6.2修改

EasyUI--增删改查EasyUI--增删改查

 

上一篇:abp(net core)+easyui+efcore实现仓储管理系统——菜单 (十六)


下一篇:easyui增删改查