最终完毕CRUD的功能了,注意,这里会对前面有一些修改,UserController的listUser() 已经改写了,如今把所有整理一下吧。

JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<meta name="description" content="easyui help you build your web page easily!">
<title>jQuery EasyUI CRUD Demo</title>
<link rel="stylesheet" type="text/css" href="css/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="css/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="css/easyui/demo.css">
<script type="text/javascript" src="js/jquery-easyui-1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-easyui-1.4.2/jquery.easyui.min.js"></script>
<style type="text/css">
#fm{
margin:0;
padding:10px 30px;
}
.ftitle{
font-size:14px;
font-weight:bold;
color:#666;
padding:5px 0;
margin-bottom:10px;
border-bottom:1px solid #ccc;
}
.fitem{
margin-bottom:5px;
}
.fitem label{
display:inline-block;
width:80px;
}
</style>
<script type="text/javascript">
var url;
function newUser(){
$('#dlg').dialog('open').dialog('setTitle','新建用户');
$('#fm').form('clear');
url = 'user/addUser';
}
function editUser(){
var row = $('#dg').datagrid('getSelected');
// alert(row.userId); if (row){
$('#dlg').dialog('open').dialog('setTitle','编辑用户');
$('#fm').form('load',row);
//url = 'user/updateUser?id='+row.userId;
url ='user/updateUser';
}
}
function saveUser(){
$('#fm').form('submit',{
//url:'user/addUser',
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.success){
$.messager.show({
title:'Info',
msg:result.msg,
showType:'fade',
style:{
right:'',
bottom:''
}
});
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({
title: 'Error',
msg: result.msg
});
}
}
});
}
function removeUser(){
var row = $('#dg').datagrid('getSelected');
//alert(row.id);
if (row){
$.messager.confirm('Confirm','你确定要删除用户吗?',function(r){
if (r){
$.post('user/removeUser',{id:row.userId},function(result){
if (result.success){
$.messager.show({
title:'Info',
msg:result.msg,
showType:'fade',
style:{
right:'',
bottom:''
}
});
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.msg
});
}
},'json');
}
});
}
}
function doSearch(){
$('#dg').datagrid('load',{
queryUserId: $('#userId').val()
});
} </script>
</head>
<body>
<h2>Basic CRUD Application</h2>
<div class="demo-info" style="margin-bottom:10px">
<div class="demo-tip icon-tip"> </div>
<div>Click the buttons on datagrid toolbar to do crud actions.</div>
</div> <table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
url="user/listUsers"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="userId" width="50">UserId</th>
<th field="userName" width="50">UserName</th>
<th field=passWord width="50">PassWord</th>
<th field="enable" width="50">Enable</th>
</tr>
</thead>
</table>
<div id="toolbar">
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a>
<div>
<span>User ID:</span>
<input id="userId" style="line-height:26px;border:1px solid #ccc">
<a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="doSearch()">Search</a>
</div>
</div> <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<div class="ftitle">User Information</div>
<form id="fm" method="post" novalidate>
<div class="fitem">
<label>UserId:</label>
<input name="userId" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>UserName:</label>
<input name="userName" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>PassWord:</label>
<input name="passWord">
</div>
<div class="fitem">
<label>Enable:</label>
<input name="enable" class="easyui-validatebox" >
</div>
</form>
</div>
<div id="dlg-buttons">
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a>
</div>
</body>
</html>

Controller:

package com.yang.bishe.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import com.yang.bishe.entity.Grid;
import com.yang.bishe.entity.Json;
import com.yang.bishe.entity.User;
import com.yang.bishe.service.interfaces.IUserService; @Controller
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
private IUserService userService;
@RequestMapping("/list")
public ModelAndView goList(){
return new ModelAndView("user/list");
}
@RequestMapping("/listUsers")
public String listUser(HttpServletRequest request,
HttpServletResponse response) throws Exception {
page=ServletRequestUtils.getIntParameter(request, "page", 1);//默认值为1
rows=ServletRequestUtils.getIntParameter(request, "rows", 0);
String queryUserId=request.getParameter("queryUserId");//获取要查询的用户账号
Grid grid = new Grid();
String hql;
List<User>users;
if(queryUserId!=null)
{
hql="from User as user where user.UserId like '%"+queryUserId+"%'";
}else{
hql="from User";
}
users=(List<User>)userService.find(hql, page, rows);
grid.setTotal(userService.count("select count(*)"+ hql));
grid.setRows(users);
writeJson(grid,response);
return null;
} @RequestMapping("/addUser")
public String addUser(User user,HttpServletRequest request,
HttpServletResponse response) throws Exception{
Json json = new Json();//用于向前端发送消息
if(userService.getById(user.getUserId())!=null){
json.setMsg("新建用户失败,用户已存在!");
}else{
userService.save(user);
json.setMsg("新建用户成功!");
json.setSuccess(true);
}
writeJson(json,response);
return null;
}
@RequestMapping("/removeUser")
public String removeUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
Json json = new Json();//用于向前端发送消息
String userId=request.getParameter("id");
try{
userService.delete((User)userService.getById(userId));//不懂为啥要加上(User)才对。。
json.setMsg("删除成功!");
json.setSuccess(true);
writeJson(json,response);
return null;
}catch (Exception e){
json.setMsg("删除失败!"+e.getMessage());
writeJson(json,response);
return null;
} }
@RequestMapping("/updateUser")
public String updateUser(User user,HttpServletResponse response) throws Exception{
Json json = new Json();//用于向前端发送消息
try{
userService.update(user);
json.setMsg("更新成功!");
json.setSuccess(true);
writeJson(json,response);
return null;
}catch(Exception e){
json.setMsg("更新失败!"+e.getMessage());
writeJson(json,response);
return null;
} }
}

事实上listUser里面一些逻辑能够放到service上的,还没弄。。。

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

package com.yang.bishe.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.yang.bishe.dao.IBaseDao;
import com.yang.bishe.entity.User;
import com.yang.bishe.service.base.BaseServiceImpl;
import com.yang.bishe.service.interfaces.IUserService;
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
@Autowired
private IBaseDao<User> userDao;
}

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

package com.yang.bishe.dao;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map; import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; @Repository
public class BaseDaoImpl<T>implements IBaseDao<T> { @Autowired
private SessionFactory sessionFactory; /**
* 获得当前事物的session
*
* @return org.hibernate.Session
*/
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
} @Override
public Serializable save(T o) {
if (o != null) {
return getCurrentSession().save(o);
}
return null;
} @SuppressWarnings("unchecked")
@Override
public T getById(Class<T> c, Serializable id) {
return (T) getCurrentSession().get(c, id);
} @Override
public T getByHql(String hql) {
Query q = getCurrentSession().createQuery(hql);
List<T> l = q.list();
if (l != null && l.size() > 0) {
return l.get(0);
}
return null;
} @Override
public void delete(T o) {
if (o != null) {
getCurrentSession().delete(o);
}
} @Override
public void update(T o) {
if (o != null) {
getCurrentSession().update(o);
}
} @Override
public List<T> find(String hql) {
Query q = getCurrentSession().createQuery(hql);
return q.list();
} @Override
public List<T> find(String hql, int page, int rows) {
Query q = getCurrentSession().createQuery(hql);
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
} @Override
public Long count(String hql) {
// Query q = getCurrentSession().createQuery(hql).;
// return (Long) q.uniqueResult();
return (Long)getCurrentSession().createQuery(hql).list().get(0);
} @Override
public int executeHql(String hql) {
Query q = getCurrentSession().createQuery(hql);
return q.executeUpdate();
} @SuppressWarnings("unchecked")
@Override
public List<Map> findBySql(String sql) {
SQLQuery q = getCurrentSession().createSQLQuery(sql);
return q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
} @Override
public List<Map> findBySql(String sql, int page, int rows) {
SQLQuery q = getCurrentSession().createSQLQuery(sql);
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
} @Override
public int executeSql(String sql) {
SQLQuery q = getCurrentSession().createSQLQuery(sql);
return q.executeUpdate();
} @Override
public BigInteger countBySql(String sql) {
SQLQuery q = getCurrentSession().createSQLQuery(sql);
return (BigInteger) q.uniqueResult();
} }

效果图:

第二页:

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

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

改动后:

SpringMVC+easyUI 分页,查询 (完整的CRUD)的更多相关文章

  1. Mybatis+SpringMVC实现分页查询(附源码)

    Maven+Mybatis+Spring+SpringMVC实现分页查询(附源码) 一.项目搭建 关于项目搭建,小宝鸽以前写过一篇Spirng+SpringMVC+Maven+Mybatis+MySQ ...

  2. Struts2与easyui分页查询

    easyui里面分页查询:在easyui框架里面已经进行一些分装,所以我们只要进行后台分页查询即可 web.xml和struts.xml文件的配置的就不需要我多说了,和分页前代码一样,不需要更改: 需 ...

  3. Maven+Mybatis+Spring+SpringMVC实现分页查询

    转载:http://www.cnblogs.com/zhangtan/p/5846955.html 一.项目搭建 关于项目搭建,小宝鸽以前写过一篇Spirng+SpringMVC+Maven+Myba ...

  4. Maven+Mybatis+Spring+SpringMVC实现分页查询(附源代码)

    以下小宝鸽将分享一篇Mybatis分页功能的博文,以下将给出具体的步骤.跟着博主的节奏肯定能实现.另外最后还会附上整个project的源代码.假设是没有使用过maven的猿友可自行下载相关的jar包就 ...

  5. springMVC+ajax分页查询

    项目用到ajax技术的查询,查询结果很多时候要分页展示.这两天摸索了一下,在这里做一总结,方便自己随时查看, 也方便后人参考. 这里的顺序遵从从前台页面到后台控制器,业务层,Dao层,Mapper 下 ...

  6. Mybatis + SpringMVC + Maven实现分页查询

    使用Mybatis + Maven + SpringMVC 运行时,突然被需要分页查询的功能给难住了 这里推荐采用的插件是PageHelper这个插件,使用起来十分方便.该插件支持以下数据库: Ora ...

  7. 一个共通的viewModel搞定所有的分页查询一览及数据导出(easyui + knockoutjs + mvc4.0)

    前言 大家看标题就明白了我想写什么了,在做企业信息化系统中可能大家写的最多的一种页面就是查询页面了.其实每个查询页面,除了条件不太一样,数据不太一样,其它的其实都差不多.所以我就想提取一些共通的东西出 ...

  8. 商品分页查询 ego-prc 实现-easyui

    使用 easyui 的 DataGrid 控件实现商品的分页查询,DataGrid 控件提交分页所需要的 page 和rows 参数,后台响应包含总记录数 total 和需要显示的商品对象的集合 ro ...

  9. MyBatis+springMVC+easyUI (dataGirl)实现分页

    页面展示效果. 页面代码: <%@ page contentType="text/html;charset=UTF-8" language="java"  ...

随机推荐

  1. lua不同模块调用

    一.起因 由于准备把lua加入的系统中,还需把字符串解析json.下了个json的lua,目前还没有搞定.但是一个lua,调用其他lua文件模块,目前刚刚搞定. 暂作记录. 二. 模块调用测试 1. ...

  2. 【例题5-4 UVA - 156】Ananagrams

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 每个字符串如果每个字符按照升序排一下.假设他们能够互相变化. 则肯定是一样的. 根据这个东西,用一个map来判重就好. [错的次数] ...

  3. [TypeScript] Using Assertion to Convert Types in TypeScript

    Sometimes the compiler needs help figuring out a type. In this lesson we learn how to help out the c ...

  4. PHP解决约瑟夫环问题

    PHP解决约瑟夫环问题 一.总结 二.PHP解决约瑟夫环问题 约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围.从编号为k的人开始报数,数到 ...

  5. 等价变换(equivalent transformation)

    1. 加加减减 (x−b)n=(x−a+a−b)n=∑i=0n(ni)(x−a)i(a−b)n−i

  6. GDB如何调试没有符号表(未加-g选项的编译)的程序

    /********************************************************************* * Author  : Samson * Date    ...

  7. 23种设计模式——Prototype模式

    Prototype模式是提供自我复制的功能.包括浅拷贝和深拷贝. 一.Prototype模式的用途 场景1:游戏场景中有很多类似的敌人,它们的技能都一样,但是随着敌人出现的位置和不同,它们的能力也不太 ...

  8. Hbase常见异常 分类: B7_HBASE 2015-02-02 16:16 412人阅读 评论(0) 收藏

    1. HBase is able to connect to ZooKeeper but the connection closes immediately hbase(main):001:0> ...

  9. Vim 在 windows 下的应用

    常用命令的学习. 第一部分 Esc:返回到 正常模式 h j k l:左下上右 x:删除字符(normal mode) :q!:放弃所有更改并退出vim :wq:保存所有更改并退出vim i:进入编辑 ...

  10. Booth算法

    Booth算法 算法描述(载自维基百科) 对于N位乘数Y,布斯算法检查其2的补码形式的最后一位和一个隐含的低位,命名为y-1,初始值为0.对于yi, i = 0, 1, ..., N - 1,考察yi ...