最终完毕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. php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便)

    php spl标准库简介(SPL是Standard PHP Library(PHP标准库)(直接看代码实例,特别方便) 一.总结 直接看代码实例,特别方便易懂 thinkphp控制器利眠宁不支持(说明 ...

  2. 读Effective Objective-C [提高OC代码质量总结笔记第一篇:熟悉OC]

    一.OC特性 OC 为 C 语言添加了面向对象特性,是其超集; OC 使用动态绑定的消息结构,也就是,在运行时才会检查对象类型; 接收一条消息后,究竟应执行何种代码,由运行期环境来决定,而非 编译器; ...

  3. 在Linux上安装及配置MariaDB

    安装MariaDB 1.切换到root用户,首先执行rpm -qa | grep -i mysql检查一下是否有已安装的与MySQL相关的东西,如果有,使用rpm -e --nodeps mysql* ...

  4. [Http] Understand what an HTTP Request is

    Let's look at several HTTP requests to learn the basic structure of these messages, and how the vari ...

  5. iOS开发Quartz2D之八:图形上下文状态栈

    #import "DrawView.h" @implementation DrawView - (void)drawRect:(CGRect)rect { // Drawing c ...

  6. 【26.8%】【CF 46D】Parking Lot

    time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standa ...

  7. Android XMPP服务器, BOSH(Http-Binding)和WEB客户端搭建

    目标: 搭建一个XMPP服务器, 实现在web page上用javascript与自己XMPP服务器通信, 匿名登录并与任何一个XMPP(Jabber)帐户通信. (Gtalk目前尚有问题) XMPP ...

  8. Mysql用户本机登陆不成功的解决

    mysql新建一个用户,本机不能登陆,但是远程能够登陆,不知什么原因,最后查阅 http://blog.itpub.net/12679300/viewspace-1453490/ 这篇文章得以解决,进 ...

  9. [NPM] Create a bash script to replace a complex npm script

    In this lesson we will look at pulling out complex npm scripts into their own external bash scripts. ...

  10. WPF随笔(九)--使用路径动画模拟管道流体流向

    原文:WPF随笔(九)--使用路径动画模拟管道流体流向 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/lordwish/article/detail ...