SpringMVC+easyUI 分页,查询 (完整的CRUD)

终于完成CRUD的功能了,注意,这里会对前面有一些改动,UserController的listUser() 已经改写了,现在把全部整理一下吧。

JSP:

[html]  view plain  copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8. <html>  
  9. <head>  
  10.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  11.     <base href="<%=basePath%>">  
  12.     <meta name="description" content="easyui help you build your web page easily!">  
  13.     <title>jQuery EasyUI CRUD Demo</title>  
  14.         <link rel="stylesheet" type="text/css" href="css/easyui/themes/default/easyui.css">  
  15.     <link rel="stylesheet" type="text/css" href="css/easyui/themes/icon.css">  
  16.     <link rel="stylesheet" type="text/css" href="css/easyui/demo.css">  
  17.     <script type="text/javascript" src="js/jquery-easyui-1.4.2/jquery.min.js"></script>  
  18.     <script type="text/javascript" src="js/jquery-easyui-1.4.2/jquery.easyui.min.js"></script>  
  19.     <style type="text/css">  
  20.         #fm{  
  21.             margin:0;  
  22.             padding:10px 30px;  
  23.         }  
  24.         .ftitle{  
  25.             font-size:14px;  
  26.             font-weight:bold;  
  27.             color:#666;  
  28.             padding:5px 0;  
  29.             margin-bottom:10px;  
  30.             border-bottom:1px solid #ccc;  
  31.         }  
  32.         .fitem{  
  33.             margin-bottom:5px;  
  34.         }  
  35.         .fitem label{  
  36.             display:inline-block;  
  37.             width:80px;  
  38.         }  
  39.     </style>  
  40.     <script type="text/javascript">  
  41.         var url;  
  42.         function newUser(){  
  43.             $('#dlg').dialog('open').dialog('setTitle','新建用户');  
  44.             $('#fm').form('clear');  
  45.             url = 'user/addUser';  
  46.         }  
  47.         function editUser(){  
  48.             var row = $('#dg').datagrid('getSelected');  
  49.             // alert(row.userId);  
  50.           
  51.             if (row){  
  52.                 $('#dlg').dialog('open').dialog('setTitle','编辑用户');  
  53.                 $('#fm').form('load',row);  
  54.                 //url = 'user/updateUser?id='+row.userId;  
  55.                 url ='user/updateUser';  
  56.             }  
  57.         }  
  58.         function saveUser(){  
  59.             $('#fm').form('submit',{  
  60.                 //url:'user/addUser',  
  61.                 url: url,  
  62.                 onSubmit: function(){  
  63.                     return $(this).form('validate');  
  64.                 },  
  65.                 success: function(result){  
  66.                     var result = eval('('+result+')');  
  67.                     if (result.success){  
  68.                         $.messager.show({  
  69.                         title:'Info',  
  70.                         msg:result.msg,  
  71.                         showType:'fade',  
  72.                         style:{  
  73.                             right:'',  
  74.                             bottom:''  
  75.                             }  
  76.                         });  
  77.                         $('#dlg').dialog('close');      // close the dialog  
  78.                         $('#dg').datagrid('reload');    // reload the user data  
  79.                     } else {  
  80.                         $.messager.show({  
  81.                             title: 'Error',  
  82.                             msg: result.msg  
  83.                         });  
  84.                     }  
  85.                 }  
  86.             });  
  87.         }  
  88.         function removeUser(){  
  89.             var row = $('#dg').datagrid('getSelected');  
  90.              //alert(row.id);  
  91.             if (row){  
  92.                 $.messager.confirm('Confirm','你确定要删除用户吗?',function(r){  
  93.                     if (r){  
  94.                         $.post('user/removeUser',{id:row.userId},function(result){  
  95.                             if (result.success){  
  96.                                 $.messager.show({  
  97.                         title:'Info',  
  98.                         msg:result.msg,  
  99.                         showType:'fade',  
  100.                         style:{  
  101.                             right:'',  
  102.                             bottom:''  
  103.                             }  
  104.                         });  
  105.                                 $('#dg').datagrid('reload');    // reload the user data  
  106.                             } else {  
  107.                                 $.messager.show({   // show error message  
  108.                                     title: 'Error',  
  109.                                     msg: result.msg  
  110.                                 });  
  111.                             }  
  112.                         },'json');  
  113.                     }  
  114.                 });  
  115.             }  
  116.         }  
  117.         function doSearch(){  
  118.             $('#dg').datagrid('load',{  
  119.             queryUserId: $('#userId').val()  
  120.         });  
  121. }  
  122.           
  123.     </script>  
  124. </head>  
  125. <body>  
  126.     <h2>Basic CRUD Application</h2>  
  127.     <div class="demo-info" style="margin-bottom:10px">  
  128.         <div class="demo-tip icon-tip"> </div>  
  129.         <div>Click the buttons on datagrid toolbar to do crud actions.</div>  
  130.     </div>  
  131.       
  132.     <table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"  
  133.             url="user/listUsers"  
  134.             toolbar="#toolbar" pagination="true"  
  135.             rownumbers="true" fitColumns="true" singleSelect="true">  
  136.         <thead>  
  137.             <tr>  
  138.                 <th field="userId" width="50">UserId</th>  
  139.                 <th field="userName" width="50">UserName</th>  
  140.                 <th field=passWord width="50">PassWord</th>  
  141.                 <th field="enable" width="50">Enable</th>  
  142.             </tr>  
  143.         </thead>  
  144.     </table>  
  145.     <div id="toolbar">  
  146.         <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>  
  147.         <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>  
  148.         <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a>  
  149.         <div>  
  150.             <span>User ID:</span>  
  151.             <input id="userId" style="line-height:26px;border:1px solid #ccc">  
  152.             <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="doSearch()">Search</a>  
  153.         </div>  
  154.     </div>  
  155.       
  156.     <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"  
  157.             closed="true" buttons="#dlg-buttons">  
  158.         <div class="ftitle">User Information</div>  
  159.         <form id="fm" method="post" novalidate>  
  160.             <div class="fitem">  
  161.                 <label>UserId:</label>  
  162.                 <input name="userId" class="easyui-validatebox" required="true">  
  163.             </div>  
  164.             <div class="fitem">  
  165.                 <label>UserName:</label>  
  166.                 <input name="userName" class="easyui-validatebox" required="true">  
  167.             </div>  
  168.             <div class="fitem">  
  169.                 <label>PassWord:</label>  
  170.                 <input name="passWord">  
  171.             </div>  
  172.             <div class="fitem">  
  173.                 <label>Enable:</label>  
  174.                 <input name="enable" class="easyui-validatebox" >  
  175.             </div>  
  176.         </form>  
  177.     </div>  
  178.     <div id="dlg-buttons">  
  179.         <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>  
  180.         <a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a>  
  181.     </div>  
  182. </body>  
  183. </html>  
Controller:

[java]  view plain  copy
  1. package com.yang.bishe.controller;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.springframework.beans.factory.annotation.Autowired;  
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.web.bind.ServletRequestUtils;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15.   
  16. import com.yang.bishe.entity.Grid;  
  17. import com.yang.bishe.entity.Json;  
  18. import com.yang.bishe.entity.User;  
  19. import com.yang.bishe.service.interfaces.IUserService;  
  20.   
  21. @Controller  
  22. @RequestMapping("/user")  
  23. public class UserController extends BaseController {  
  24.     @Autowired  
  25.     private IUserService userService;  
  26.     @RequestMapping("/list")  
  27.        public ModelAndView goList(){  
  28.           return new ModelAndView("user/list");  
  29.         }  
  30.     @RequestMapping("/listUsers")  
  31.       public String listUser(HttpServletRequest request,  
  32.                 HttpServletResponse response) throws Exception {  
  33.         page=ServletRequestUtils.getIntParameter(request, "page"1);//默认值为1  
  34.         rows=ServletRequestUtils.getIntParameter(request, "rows"0);  
  35.         String queryUserId=request.getParameter("queryUserId");//获取要查询的用户账号  
  36.         Grid grid = new Grid();  
  37.         String hql;  
  38.         List<User>users;  
  39.         if(queryUserId!=null)  
  40.         {  
  41.             hql="from User as user where user.UserId like  '%"+queryUserId+"%'";  
  42.         }else{  
  43.             hql="from User";  
  44.         }  
  45.         users=(List<User>)userService.find(hql, page, rows);  
  46.         grid.setTotal(userService.count("select count(*)"+ hql));  
  47.         grid.setRows(users);  
  48.         writeJson(grid,response);  
  49.         return null;  
  50.         }  
  51.       
  52.     @RequestMapping("/addUser")  
  53.      public String addUser(User user,HttpServletRequest request,  
  54.                 HttpServletResponse response) throws Exception{  
  55.         Json json = new Json();//用于向前端发送消息  
  56.         if(userService.getById(user.getUserId())!=null){  
  57.             json.setMsg("新建用户失败,用户已存在!");  
  58.         }else{  
  59.             userService.save(user);  
  60.             json.setMsg("新建用户成功!");  
  61.             json.setSuccess(true);  
  62.         }  
  63.         writeJson(json,response);  
  64.         return null;  
  65.         }  
  66.     @RequestMapping("/removeUser")  
  67.      public String removeUser(HttpServletRequest request,HttpServletResponse response) throws Exception{  
  68.         Json json = new Json();//用于向前端发送消息  
  69.         String userId=request.getParameter("id");  
  70.         try{  
  71.             userService.delete((User)userService.getById(userId));//不懂为啥要加上(User)才对。。  
  72.             json.setMsg("删除成功!");  
  73.             json.setSuccess(true);  
  74.             writeJson(json,response);  
  75.             return null;  
  76.         }catch (Exception e){  
  77.             json.setMsg("删除失败!"+e.getMessage());  
  78.             writeJson(json,response);  
  79.             return null;  
  80.         }  
  81.       
  82.         }  
  83.     @RequestMapping("/updateUser")  
  84.      public String updateUser(User user,HttpServletResponse response) throws Exception{  
  85.         Json json = new Json();//用于向前端发送消息  
  86.         try{  
  87.                 userService.update(user);  
  88.                 json.setMsg("更新成功!");  
  89.                 json.setSuccess(true);  
  90.                 writeJson(json,response);  
  91.                 return null;  
  92.         }catch(Exception e){  
  93.             json.setMsg("更新失败!"+e.getMessage());  
  94.             writeJson(json,response);  
  95.             return null;  
  96.         }  
  97.           
  98.     }  
  99. }  

其实listUser里面一些逻辑可以放到service上的,还没弄。。。

service层没什么,是继承一个baseService

[java]  view plain  copy
  1. package com.yang.bishe.service.impl;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import com.yang.bishe.dao.IBaseDao;  
  7. import com.yang.bishe.entity.User;  
  8. import com.yang.bishe.service.base.BaseServiceImpl;  
  9. import com.yang.bishe.service.interfaces.IUserService;  
  10. @Service  
  11. public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {  
  12.     @Autowired  
  13.     private IBaseDao<User> userDao;  
  14. }  

userDao都是继承BaseDao的:我就贴一些用到的函数吧(接口啥的就不贴出来了):

[java]  view plain  copy
  1. package com.yang.bishe.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.math.BigInteger;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.hibernate.Query;  
  9. import org.hibernate.SQLQuery;  
  10. import org.hibernate.Session;  
  11. import org.hibernate.SessionFactory;  
  12. import org.hibernate.transform.Transformers;  
  13. import org.springframework.beans.factory.annotation.Autowired;  
  14. import org.springframework.stereotype.Repository;  
  15.   
  16. @Repository  
  17. public class BaseDaoImpl<T>implements IBaseDao<T> {  
  18.   
  19.     @Autowired  
  20.     private SessionFactory sessionFactory;  
  21.   
  22.     /** 
  23.      * 获得当前事物的session 
  24.      *  
  25.      * @return org.hibernate.Session 
  26.      */  
  27.     public Session getCurrentSession() {  
  28.         return sessionFactory.getCurrentSession();  
  29.     }  
  30.   
  31.     @Override  
  32.     public Serializable save(T o) {  
  33.         if (o != null) {  
  34.             return getCurrentSession().save(o);  
  35.         }  
  36.         return null;  
  37.     }  
  38.   
  39.     @SuppressWarnings("unchecked")  
  40.     @Override  
  41.     public T getById(Class<T> c, Serializable id) {  
  42.         return (T) getCurrentSession().get(c, id);  
  43.     }  
  44.   
  45.     @Override  
  46.     public T getByHql(String hql) {  
  47.         Query q = getCurrentSession().createQuery(hql);  
  48.         List<T> l = q.list();  
  49.         if (l != null && l.size() > 0) {  
  50.             return l.get(0);  
  51.         }  
  52.         return null;  
  53.     }  
  54.   
  55.   
  56.     @Override  
  57.     public void delete(T o) {  
  58.         if (o != null) {  
  59.             getCurrentSession().delete(o);  
  60.         }  
  61.     }  
  62.   
  63.     @Override  
  64.     public void update(T o) {  
  65.         if (o != null) {  
  66.             getCurrentSession().update(o);  
  67.         }  
  68.     }  
  69.   
  70.     @Override  
  71.     public List<T> find(String hql) {  
  72.         Query q = getCurrentSession().createQuery(hql);  
  73.         return q.list();  
  74.     }  
  75.   
  76.   
  77.     @Override  
  78.     public List<T> find(String hql, int page, int rows) {  
  79.         Query q = getCurrentSession().createQuery(hql);  
  80.         return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();  
  81.     }  
  82.   
  83.     @Override  
  84.     public Long count(String hql) {  
  85. //      Query q = getCurrentSession().createQuery(hql).;  
  86. //      return (Long) q.uniqueResult();  
  87.         return  (Long)getCurrentSession().createQuery(hql).list().get(0);  
  88.     }  
  89.   
  90.   
  91.     @Override  
  92.     public int executeHql(String hql) {  
  93.         Query q = getCurrentSession().createQuery(hql);  
  94.         return q.executeUpdate();  
  95.     }  
  96.   
  97.   
  98.     @SuppressWarnings("unchecked")  
  99.     @Override  
  100.     public List<Map> findBySql(String sql) {  
  101.         SQLQuery q = getCurrentSession().createSQLQuery(sql);  
  102.         return q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();  
  103.     }  
  104.   
  105.     @Override  
  106.     public List<Map> findBySql(String sql, int page, int rows) {  
  107.         SQLQuery q = getCurrentSession().createSQLQuery(sql);  
  108.         return q.setFirstResult((page - 1) * rows).setMaxResults(rows).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();  
  109.     }  
  110.   
  111.   
  112.     @Override  
  113.     public int executeSql(String sql) {  
  114.         SQLQuery q = getCurrentSession().createSQLQuery(sql);  
  115.         return q.executeUpdate();  
  116.     }  
  117.   
  118.     @Override  
  119.     public BigInteger countBySql(String sql) {  
  120.         SQLQuery q = getCurrentSession().createSQLQuery(sql);  
  121.         return (BigInteger) q.uniqueResult();  
  122.     }  
  123.   
  124. }  

效果图:


第二页:


根据userId查找,这里是模糊查询:



编辑用户(弹出的对话框会获取选中的数据):


修改后:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值