Easyui增删改查

转自:http://blog.csdn.net/liu1765686161/article/details/48010097

1.前台html

  1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2 <html xmlns="http://www.w3.org/1999/xhtml">
  3 <head>
  4 <title>管理后台.................</title>
  5  
  6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  7 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  8 <script type="text/JavaScript" src="/ck-bs/jQuery-easy-ui/jquery.min.js"></script>
  9 <script type="text/javascript" src="/ck-bs/jquery-easy-ui/jquery.cookie.js"></script>
 10 <link id="easyuiTheme" rel="stylesheet" type="text/css" href="/ck-bs/jquery-easy-ui/themes/default/easyui.css"/>
 11 <script type="text/javascript" src="/ck-bs/jquery-easy-ui/changeEasyuiTheme.js"></script>
 12 <link rel="stylesheet" type="text/css" href="/ck-bs/jquery-easy-ui/themes/icon.css"/>
 13 <script type="text/javascript" src="/ck-bs/jquery-easy-ui/jquery.easyui.min.js"></script>
 14 <script type="text/javascript" src="/ck-bs/jquery-easy-ui/locale/easyui-lang-zh_CN.js"></script>
 15 <script type="text/javascript" src="/ck-bs/js/util.js"></script>
 16 <script type="text/javascript" src="/ck-bs/js/validatebox.js"></script>
 17 <script type="text/javascript" src="/ck-bs/js/common.js"></script>
 18 <script type="text/javascript" src="/ck-bs/jquery-easy-ui/Chart.js"></script>
 19 <style type="text/css">
 20 .datagrid-view{
 21     height: 500px;
 22 }
 23 </style>
 24 </head>
 25 <body>
 26     <div id="toolbar" style="padding:5px;height:auto">  
 27         <div>    
 28             <span>处理状态:</span>
 29                             <select id="regSource" class="easyui-combobox">   
 30                                 <option value="weixin">微信</option>   
 31                                 <option value="zfb">支付宝</option>    
 32                                 <option value="qq">QQ</option>    
 33                                 <option value="mobile">手机</option>    
 34                             </select>     
 35         <a href="javascript:search()" class="easyui-linkbutton" data-options="iconCls:'icon-search'">查询</a>
 36         <a href="javascript:reset()" class="easyui-linkbutton" data-options="iconCls:'icon-clear'">重置</a>    
 37         </div>     
 38         <div style="margin-bottom:5px">    
 39             <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addUserInfo()">添加</a>    
 40             <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUserInfo()">修改</a>   
 41             <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="delUser()">删除</a>   
 42             <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editRole()">分配角色</a> 
 43         </div>     
 44     </div>    
 45         <table id="users_tb" class="easyui-datagrid" style="100%;height:100%;font-size:15px">
 46         </table>
 47     
 48     <!-- 用户信息窗口 -->
 49     <div id="userInfoWin" class="easyui-window" title="用户信息"
 50         style=" 500px; height: auto;" closed="true">
 51         <form id="userInfoForm" style="padding: 10px 20px 10px 40px;" method="post" enctype="multipart/form-data">
 52             <input type="hidden" name="userId"/>
 53             <table align="center">
 54                     <tr>
 55                         <td>用户头像:</td>
 56                         <td>
 57                             <input class="easyui-filebox"  data-options="prompt:'请选择...',buttonText:'上传图片',onChange:function(){checkUploadUserPic(this)}"
 58                              name="userIcon"  id="userIcon" style="310px"/> 
 59                          </td>
 60                     </tr>
 61                     <tr>
 62                         <td>注册来源:</td>
 63                         <td >
 64                             <select id="regSource" class="easyui-combobox" style="310px" name="regSource" style="200px;">   
 65                                 <option value="weixin">微信</option>   
 66                                 <option value="zfb">支付宝</option>    
 67                                 <option value="qq">QQ</option>    
 68                                 <option value="mobile">手机</option>    
 69                             </select> 
 70                         </td>
 71                     </tr>
 72                     <tr>
 73                         <td>用户类型:</td>
 74                         <td>
 75                             <select id="userType" class="easyui-combobox" style="310px" name="userType" style="200px;">   
 76                                 <option value="COMMON">普通用户</option> 
 77                                 <option value="SYS">管理员</option>      
 78                                 <option value="SUPPLIER">供应商</option>    
 79                             </select> 
 80                         </td>
 81                     </tr>
 82                     <tr>
 83                         <td>用户状态:</td>
 84                         <td>
 85                             <select id="userState" class="easyui-combobox" style="310px" name="userState" style="200px;">   
 86                                 <option value="1">有效</option>   
 87                                 <option value="0">冻结</option>    
 88                                 <option value="2">审核中</option>    
 89                             </select> 
 90                         </td>
 91                     </tr>
 92                     <tr>
 93                         <td>用户名:</td>
 94                         <td><input class="easyui-textbox" type="text" name="nickName" style="310px" data-options="required:true,validType:'length[0,100]'"/></td>
 95                     </tr>
 96                     <tr>
 97                         <td>密码:</td>
 98                         <td><input class="easyui-textbox" type="text" name="userPwd" style="310px"  data-options="required:true,validType:'length[0,100]'"/></td>
 99                     </tr>
100                 </table>
101                 
102             <div style="padding: 5px; text-align: center;">
103                 <a href="#" class="easyui-linkbutton" icon="icon-ok" onclick="javascript:saveUsers()">确定</a> <a
104                     href="#" class="easyui-linkbutton" icon="icon-cancel" onclick="javascript:$('#win').window('close')">取消</a>
105             </div>
106         </form>
107     </div>
108 
109     <!-- 权限编辑窗口 -->
110     <div id="win" class="easyui-window" title="分配角色"
111         style=" 500px; height: auto;" closed="true">
112         <form id="userrole" style="padding: 10px 20px 10px 40px;">
113             <input type="hidden" name="userId" id="edituserId"/>
114             <div style="padding: 5px; text-align: center;">
115                 角色(可多选):<select class="easyui-combobox" id="editrolesIds" name="rolesIds" data-options="multiple:true" style="200px;"></select>
116             </div>
117             <div style="padding: 5px; text-align: center;">
118                 <a href="#" class="easyui-linkbutton" icon="icon-ok" onclick="javascript:saveUserRole()">确定</a> <a
119                     href="#" class="easyui-linkbutton" icon="icon-cancel" onclick="javascript:$('#win').window('close')">取消</a>
120             </div>
121         </form>
122     </div>
123 <script type="text/javascript" src="../../js/user/users.js"></script>
124 </body>
125 </html>

2.前台js

  1 /**图片上传格式验证*/
  2 function checkUploadUserPic(obj){
  3     var filepath =$(obj).filebox('getValue');
  4     if(filepath==""){
  5        //alert("请选择上传的文件!");
  6        return false;
  7     }
  8     var extname = filepath.substring(filepath.lastIndexOf(".")+1,filepath.length);
  9    extname = extname.toLowerCase();//处理了大小写
 10     if(extname!= "bmp"&&extname!= "jpg"&&extname!= "gif"&&extname!= "png"){
 11      alert("只能上传bmp,jpg,gif,png格式的图片!");
 12      $(obj).filebox('setValue','');
 13      return false;
 14     }
 15    }
 16 
 17 
 18 /**
 19  * 初始化界面
 20  */
 21 var dataGrid;
 22 var rowEditor = undefined;
 23 var editRow = undefined;
 24 $(function() {
 25     dataGrid = $('#users_tb').datagrid(
 26                     {
 27                         url : "../../service/Users/all",// 加载的URL
 28                         isField : "userId",
 29                         method : "POST",
 30                         pagination : false,// 显示分页
 31                         fit : true,// 自动补全
 32                         fitColumns : true,
 33                         pagination:true,
 34                         rownumbers:true,
 35                         singleSelect : true,
 36                         iconCls : "icon-save",// 图标
 37                         columns : [ [ // 每个列具体内容
 38                                       
 39                                       {
 40                                             field:"userId",
 41                                             title:"ID",
 42                                             40
 43                                          },
 44                                          {
 45                                                 field:"rolesIds",
 46                                                 title:"用户角色",
 47                                                 hidden:true
 48                                              },
 49                                          {
 50                                               field:"userIcon",
 51                                               title:"用户头像",
 52                                               80,
 53                                               formatter : function(value, row, index) {
 54                                                     return '<img class="easyui-img" style=" 40px;height: 40px;" src="../../upload/users/'+value+'"></img>';
 55                                             }
 56                                           },
 57                                           {
 58                                               field:"regSource",
 59                                               title:"注册来源",
 60                                               80,
 61                                               formatter : function(value, row, index) {
 62                                                     if (value == 'weixin') {
 63                                                         return '<span>微信</span>';
 64                                                     } else if (value == 'zfb') {
 65                                                         return '<span>支付宝</span>';
 66                                                     } else if (value == 'qq') {
 67                                                         return '<span>QQ</span>';
 68                                                     } else {
 69                                                         return '<span>手机</span>';
 70                                                     }
 71                                                 }
 72                                           },
 73                                           {
 74                                               field:"userType",
 75                                               title:"用户类型",
 76                                               80,
 77                                                 formatter : function(value, row, index) {
 78                                                     if (value == 'SYS') {
 79                                                         return '<span>管理员</span>';
 80                                                     } else if (value == 'COMMON') {
 81                                                         return '<span>普通用户</span>';
 82                                                     } else {
 83                                                         return '<span>供应商</span>';
 84                                                     }
 85                                                 }
 86                                           },
 87                                           {
 88                                                 field:"userState",
 89                                                 title:"用户状态",
 90                                                 80,
 91                                                 formatter : function(value, row, index) {
 92                                                     if (value == '1') {
 93                                                         return '<span>有效</span>';
 94                                                     } else if (value == '0') {
 95                                                         return '<span>冻结</span>';
 96                                                     } else {
 97                                                         return '<span>审核中</span>';
 98                                                     }
 99                                                 }
100                                           },
101                                           {
102                                                  field:"userPwd",
103                                                 title:"用户密码",
104                                                 80
105                                           },
106                                           {
107                                                 field:"nickName",
108                                                 title:"用户名",
109                                                 80
110                                           },
111                                           {
112                                                 field:"regTm",
113                                                 title:"创建时间",
114                                                 80
115                                                 
116                                           }
117                                 
118                                  ] ],
119                         toolbar : "#toolbar" // 工具条
120                     });
121 
122     var pager = $("#users_tb").datagrid('getPager');
123     $(pager).pagination({
124         pageSize:10,
125         pageList:[5,10,15,20],
126         beforePageText: '第',//页数文本框前显示的汉字 
127         afterPageText: '页    共 {pages} 页',
128         displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',
129         onBeforeRefresh:function(){ 
130             $(this).pagination('loading');//正在加载数据中...
131             //alert('正在加载数据中...');
132             $(this).pagination('loaded'); //数据加载完毕
133         }
134     });
135 });
136 
137 function reset(){
138     $("#regSource").combobox('setValue','');
139 }
140 //获取参数       
141 function getQueryParams(queryParams) {  
142     var regSource = $("#regSource").combobox('getValue');
143     queryParams.regSource = regSource;  
144     return queryParams;  
145 }  
146 
147 //增加查询参数,重新加载表格  
148 function search() {  
149        //查询参数直接添加在queryParams中      
150        var queryParams = $('#users_tb').datagrid('options').queryParams;  
151        getQueryParams(queryParams);  
152        $('#users_tb').datagrid('options').queryParams = queryParams;  
153        $("#users_tb").datagrid('reload');  
154 } 
155 
156 function editUserInfo(){
157     var rows = dataGrid.datagrid('getSelections');
158     if (rows.length == 1) {
159         var row =rows[0];
160         $("#userInfoWin").window('open');
161         $("#userInfoForm").form("load", row);
162     }else{
163         alert("请选择一条记录!");
164         return;
165     }
166 }
167 
168 function addUserInfo(){
169     $("#userInfoWin").window('open');
170     $("#userInfoForm").form("clear");
171 }
172 
173 
174 function editRole(){
175     var rows = dataGrid.datagrid('getSelections');
176     if (rows.length == 1) {
177         var row =rows[0];
178         $('#editrolesIds').combobox({  
179             url : '../../service/role/all', 
180             valueField:'id',    
181             textField:'roleName'   
182         }); 
183         $("#win").window('open');
184         if(row[0].rolesIds!=null&&row[0].rolesIds!="undefined"&&row[0].rolesIds!=""){
185             $("#editrolesIds").val(row[0].rolesIds);
186         }
187         $("#edituserId").val(row[0].userId);
188     }else{
189         alert("请选择一条记录!");
190         return;
191     }
192 }
193 
194 function delUser(){
195     var rows = dataGrid
196     .datagrid('getSelections');
197 
198 if (rows.length <= 0) {
199 $.messager.alert('警告', '您没有选择',
200         'error');
201 } else if (rows.length > 1) {
202 $.messager.alert('警告', '不支持批量删除',
203         'error');
204 } else {
205 $.messager.confirm('确定','您确定要删除吗',
206         function(t) {
207             if (t) {
208                 $.ajax({
209                     url : '../../service/Users/del',
210                     method : 'POST',
211                     data : rows[0],
212                     dataType : 'json',
213                     success : function(r) {
214                         if (r.code=="1") {
215                             dataGrid.datagrid('acceptChanges');
216                             $.messager.show({msg : r.msg,title : '成功'});
217                             editRow = undefined;
218                             dataGrid.datagrid('reload');
219                         } else {
220                             dataGrid.datagrid('beginEdit',editRow);
221                             $.messager.alert('错误',r.msg,'error');
222                         }
223                         dataGrid.datagrid('unselectAll');
224                     }
225                     });
226                     }
227                 });
228 }
229 }
230 
231 function saveUserRole(){
232     $('#userrole').form('submit',{
233         url : '../../service/UsersRoles/update',
234         method:'post',
235         success:function(data){
236             var r = JSON.parse(data);
237             if(r.code=="1"){
238                 $.messager.alert({
239                     msg : "角色分配成功",
240                     title : '成功'
241                 });
242                 $('#win').window('close');
243                 $("#users_tb").datagrid('reload');
244             }else{
245                 $.messager.alert(
246                         '错误',
247                         "角色分配失败",
248                         'error');
249             }
250             $('#win').window('close');
251             $("#users_tb").datagrid('reload');
252         }
253     });
254 }
255 
256 function saveUsers(){
257     $('#userInfoForm').form('submit',{
258         url: '../../service/Users/save',
259         method:'post',
260         enctype : "multipart/form-data",
261         success:function(data){
262             var r = JSON.parse(data);
263             if(r.code=="1"){
264                 $.messager.alert({
265                     msg : "操作用户成功",
266                     title : '成功'
267                 });
268                 $('#userInfoWin').window('close');
269                 $("#users_tb").datagrid('reload');
270             }else{
271                 $.messager.alert(
272                         '错误',
273                         "操作用户失败",
274                         'error');
275             }
276             $('#userInfoWin').window('close');
277             $("#users_tb").datagrid('reload');
278         }
279     });
280 }

3.后台代码

/**
 * 
 */
package com.aiw.ck.controller.user;

import Java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.aiw.ck.controller.BaseController;
import com.aiw.ck.data.Res;
import com.aiw.ck.data.WebConstants;
import com.aiw.ck.model.user.User;
import com.aiw.ck.util.FileUploadUtil;
import com.aiw.ck.util.StrUtil;
import com.google.gson.Gson;



/**
 * 用户管理
 * @author sfit0512
 *
 */
@RestController
public class UsersController extends BaseController {
    
    Logger log = Logger.getLogger(UsersController.class);
    
    @Autowired
    private com.aiw.ck.service.user.UserService userService;

    private Gson gson = new Gson();
    /**
     * 分页查询用户
     * @return
     */
    @RequestMapping("/Users/all")
    public String getUserssQueryPage(HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String regSource = request.getParameter("regSource");
            String pageString = request.getParameter("page");
            String rowsString = request.getParameter("rows");
            log.info("parameter: regSource:"+regSource+" page:"+pageString+" rows:"+rowsString);
            int pages = 1;
            int rows = 20;

            if(StrUtil.notBlank(pageString)){
                pages = Integer.parseInt(pageString);
            }
            if(StrUtil.notBlank(rowsString)){
                rows = Integer.parseInt(rowsString);
            }
            List<User> list = userService.getUsers(regSource,pages, rows);
            if (list.size()>0) {
                long total = userService.getTotalCount(regSource);
                Map<String, Object> ret = new HashMap<String, Object>();
                ret.put("total", total);
                ret.put("rows", list);
                return gson.toJson(ret);
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("",e);
            return FAIL;
        }
        return FAIL;
    }
    
    
    /**
     * 添加用户
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/Users/add", method = RequestMethod.POST)
    @ResponseBody
    public Res addUsers(HttpServletRequest request,
            HttpServletResponse response,User user) throws Exception {
        try {
            int ret = userService.addUser(user);
            if(ret>0){
                return success();
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("UsersController 的方法 addUsers 执行出错,原因:" + e, e);
        }
        return fail();
    }
    
    /**
     * 修改用户
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/Users/update", method = RequestMethod.POST)
    @ResponseBody
    public Res updateUsers(HttpServletRequest request,
            HttpServletResponse response ,User user) throws Exception {
        try {
            int ret = userService.updateUser(user);
            if(ret>0){
                return success();
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("UsersController 的方法 updateUsers 执行出错,原因:" + e, e);
        }
        return fail();
    }
    
    /**
     * 保存用户
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/Users/save", method = RequestMethod.POST)
    @ResponseBody
    public Res saveUsers(@RequestParam("userIcon") CommonsMultipartFile userIcon,
            HttpServletRequest request,HttpServletResponse response) throws Exception {
        try {

            String regSource = request.getParameter("regSource");
            String userId = request.getParameter("userId");
            String userType =  request.getParameter("userType");
            String nickName = request.getParameter("nickName");
            String userPwd = request.getParameter("userPwd");
            String userState = request.getParameter("userState");
            String uString = "";
            User user = new User();
            //文件存储路径
            String path =request.getSession().getServletContext().getRealPath("/")+WebConstants.FILE_UPLOAD_USERS;
            if (userIcon.getSize()>0) {
                 uString = userIcon.getFileItem().getName();
                //上传图片
                 FileUploadUtil.fileUpload(userIcon, path,uString);
                 user.setUserIcon(uString);
            }
            user.setNickName(nickName);
            user.setUserPwd(userPwd);
            user.setRegSource(regSource);
            user.setUserType(userType);
            user.setUserState(userState.charAt(0));
            int ret = 0;
            if (StrUtil.notBlank(userId)) {
                //修改用户信息
                user.setUserId(Long.parseLong(userId));
                ret = userService.updateUser(user);
            } else {
                ret = userService.addUser(user);
            }
            if(ret>0){
                return success();
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("UsersController 的方法 updateUsers 执行出错,原因:" + e, e);
        }
        return fail();
    }
    
    
    
    /**
     * 删除用户
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/Users/del", method = RequestMethod.POST)
    @ResponseBody
    public Res deleteUsers(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            String id = request.getParameter("userId");
            int ret = userService.delUser(Long.parseLong(id));
            if(ret>0){
                return success();
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("UsersController 的方法 deleteUsers 执行出错,原因:" + e, e);
        }
        return fail();
    }
    
    
    /**
     * 添加用户角色关系
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/UsersRoles/add", method = RequestMethod.POST)
    @ResponseBody
    public Res addUsersRoles(HttpServletRequest request,
            HttpServletResponse response,User user) throws Exception {
        try {
            int ret = userService.addUserRoles(user);
            if(ret>0){
                return success();
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("UsersController 的方法 addUsersRoles 执行出错,原因:" + e, e);
        }
        return fail();
    }
    
    /**
     * 修改用户角色关系
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/UsersRoles/update", method = RequestMethod.GET)
    @ResponseBody
    public Res updateUsersRoles(HttpServletRequest request,
            HttpServletResponse response ,User user) throws Exception {
        try {
            int ret = userService.updateUserRoles(user);
            if(ret>0){
                return success();
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("UsersController 的方法 updateUsersRoles 执行出错,原因:" + e, e);
        }
        return fail();
    }
    

}
原文地址:https://www.cnblogs.com/Thinkingcao/p/7274094.html