终于完成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" οnclick="newUser()">New User</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-edit" plain="true" οnclick="editUser()">Edit User</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-remove" plain="true" οnclick="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" οnclick="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" οnclick="saveUser()">Save</a>
<a href="javascript:void(0);" class="easyui-linkbutton" iconCls="icon-cancel" οnclick="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查找,这里是模糊查询:
编辑用户(弹出的对话框会获取选中的数据):
修改后: