1.前台html
/**图片上传格式验证*/
function checkUploadUserPic(obj){
var filepath =$(obj).filebox('getValue');
if(filepath==""){
//alert("请选择上传的文件!");
return false;
}
var extname = filepath.substring(filepath.lastIndexOf(".")+1,filepath.length);
extname = extname.toLowerCase();//处理了大小写
if(extname!= "bmp"&&extname!= "jpg"&&extname!= "gif"&&extname!= "png"){
alert("只能上传bmp,jpg,gif,png格式的图片!");
$(obj).filebox('setValue','');
return false;
}
}
/**
* 初始化界面
*/
var dataGrid;
var rowEditor = undefined;
var editRow = undefined;
$(function() {
dataGrid = $('#users_tb').datagrid(
{
url : "../../service/Users/all",// 加载的URL
isField : "userId",
method : "POST",
pagination : false,// 显示分页
fit : true,// 自动补全
fitColumns : true,
pagination:true,
rownumbers:true,
singleSelect : true,
iconCls : "icon-save",// 图标
columns : [ [ // 每个列具体内容
{
field:"userId",
title:"ID",
width:40
},
{
field:"rolesIds",
title:"用户角色",
hidden:true
},
{
field:"userIcon",
title:"用户头像",
width:80,
formatter : function(value, row, index) {
return '';
}
},
{
field:"regSource",
title:"注册来源",
width:80,
formatter : function(value, row, index) {
if (value == 'weixin') {
return '微信';
} else if (value == 'zfb') {
return '支付宝';
} else if (value == 'qq') {
return 'QQ';
} else {
return '手机';
}
}
},
{
field:"userType",
title:"用户类型",
width:80,
formatter : function(value, row, index) {
if (value == 'SYS') {
return '管理员';
} else if (value == 'COMMON') {
return '普通用户';
} else {
return '供应商';
}
}
},
{
field:"userState",
title:"用户状态",
width:80,
formatter : function(value, row, index) {
if (value == '1') {
return '有效';
} else if (value == '0') {
return '冻结';
} else {
return '审核中';
}
}
},
{
field:"userPwd",
title:"用户密码",
width:80
},
{
field:"nickName",
title:"用户名",
width:80
},
{
field:"regTm",
title:"创建时间",
width:80
}
] ],
toolbar : "#toolbar" // 工具条
});
var pager = $("#users_tb").datagrid('getPager');
$(pager).pagination({
pageSize:10,
pageList:[5,10,15,20],
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '当前显示 {from} - {to} 条记录 共 {total} 条记录',
onBeforeRefresh:function(){
$(this).pagination('loading');//正在加载数据中...
//alert('正在加载数据中...');
$(this).pagination('loaded'); //数据加载完毕
}
});
});
function reset(){
$("#regSource").combobox('setValue','');
}
//获取参数
function getQueryParams(queryParams) {
var regSource = $("#regSource").combobox('getValue');
queryParams.regSource = regSource;
return queryParams;
}
//增加查询参数,重新加载表格
function search() {
//查询参数直接添加在queryParams中
var queryParams = $('#users_tb').datagrid('options').queryParams;
getQueryParams(queryParams);
$('#users_tb').datagrid('options').queryParams = queryParams;
$("#users_tb").datagrid('reload');
}
function editUserInfo(){
var rows = dataGrid.datagrid('getSelections');
if (rows.length == 1) {
var row =rows[0];
$("#userInfoWin").window('open');
$("#userInfoForm").form("load", row);
}else{
alert("请选择一条记录!");
return;
}
}
function addUserInfo(){
$("#userInfoWin").window('open');
$("#userInfoForm").form("clear");
}
function editRole(){
var rows = dataGrid.datagrid('getSelections');
if (rows.length == 1) {
var row =rows[0];
$('#editrolesIds').combobox({
url : '../../service/role/all',
valueField:'id',
textField:'roleName'
});
$("#win").window('open');
if(row[0].rolesIds!=null&&row[0].rolesIds!="undefined"&&row[0].rolesIds!=""){
$("#editrolesIds").val(row[0].rolesIds);
}
$("#edituserId").val(row[0].userId);
}else{
alert("请选择一条记录!");
return;
}
}
function delUser(){
var rows = dataGrid
.datagrid('getSelections');
if (rows.length <= 0) {
$.messager.alert('警告', '您没有选择',
'error');
} else if (rows.length > 1) {
$.messager.alert('警告', '不支持批量删除',
'error');
} else {
$.messager.confirm('确定','您确定要删除吗',
function(t) {
if (t) {
$.ajax({
url : '../../service/Users/del',
method : 'POST',
data : rows[0],
dataType : 'json',
success : function(r) {
if (r.code=="1") {
dataGrid.datagrid('acceptChanges');
$.messager.show({msg : r.msg,title : '成功'});
editRow = undefined;
dataGrid.datagrid('reload');
} else {
dataGrid.datagrid('beginEdit',editRow);
$.messager.alert('错误',r.msg,'error');
}
dataGrid.datagrid('unselectAll');
}
});
}
});
}
}
function saveUserRole(){
$('#userrole').form('submit',{
url : '../../service/UsersRoles/update',
method:'post',
success:function(data){
var r = JSON.parse(data);
if(r.code=="1"){
$.messager.alert({
msg : "角色分配成功",
title : '成功'
});
$('#win').window('close');
$("#users_tb").datagrid('reload');
}else{
$.messager.alert(
'错误',
"角色分配失败",
'error');
}
$('#win').window('close');
$("#users_tb").datagrid('reload');
}
});
}
function saveUsers(){
$('#userInfoForm').form('submit',{
url: '../../service/Users/save',
method:'post',
enctype : "multipart/form-data",
success:function(data){
var r = JSON.parse(data);
if(r.code=="1"){
$.messager.alert({
msg : "操作用户成功",
title : '成功'
});
$('#userInfoWin').window('close');
$("#users_tb").datagrid('reload');
}else{
$.messager.alert(
'错误',
"操作用户失败",
'error');
}
$('#userInfoWin').window('close');
$("#users_tb").datagrid('reload');
}
});
}
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
if (list.size()>0) {
long total = userService.getTotalCount(regSource);
Map
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();
}
}