mybatis plus + spring boot + shiro:
entity:
package com.aaa.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 用户信息表
* </p>
*
* @author AAATeacherChen
* @since 2020-07-09
*/
@Data
public class UserVo implements Serializable{
private static final long serialVersionUID = 1L;
/**
* 用户ID
*/
private Integer userId;
/**
* 部门ID
*/
private Integer deptId;
/**
* 登录账号
*/
private String loginName;
/**
* 用户昵称
*/
private String userName;
/**
* 用户邮箱
*/
private String email;
/**
* 手机号码
*/
private String phonenumber;
/**
* 用户性别(0男 1女 2未知)
*/
private String sex;
private String avatar;
/**
* 密码
*/
private String password;
/**
* 盐加密
*/
private String salt;
/**
* 帐号状态(0正常 1停用)
*/
private String status;
/**
* 删除标志(0代表存在 2代表删除)
*/
private String delFlag;
/**
* 创建者
*/
private String createBy;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新者
*/
private String updateBy;
/**
* 更新时间
*/
private Date updateTime;
/**
* 备注
*/
private String remark;
/**
* 实体多对多
*/
private Dept dept;
}
dao:
@Mapper
@Repository
//@CacheNamespace(implementation= MybatisCache.class,eviction=MybatisCache.class)
public interface UserDao extends BaseMapper<User> {
List<UserVo> selectUserVoList(Page<UserVo> pageInfo, @Param("condition") Map<String ,Object> condition);
int updateUserColumById(User user);
int resetPassword(User user);
}
service:
public interface UserService extends IService<User> {
List<UserVo> selectUserVoList( Page<UserVo> pageInfo, Map<String ,Object> condition);
boolean saveUserAndSalt(User user);
boolean updateUserAndSalt(User user);
boolean resetPassword(User user);
}
Impl:
package com.aaa.service.impl;
import com.aaa.dao.UserRoleDao;
import com.aaa.entity.User;
import com.aaa.dao.UserDao;
import com.aaa.entity.UserRole;
import com.aaa.entity.UserVo;
import com.aaa.service.UserService;
import com.aaa.shiro.ShiroUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* <p>
* 用户信息表 服务实现类
* </p>
*
* @author AAATeacherChen
* @since 2020-07-09
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private UserRoleDao userRoleDao;
@Override
public List<UserVo> selectUserVoList( Page<UserVo> pageInfo, Map<String ,Object> condition) {
List<UserVo> userVoList = userDao.selectUserVoList(pageInfo, condition);
return userVoList;
}
/**
* create by: Teacher陈
* description: 保存用户之前,对密码进行加盐加密
* create time: 2020/7/23 16:05
*
* @return a
* @Param: null
*/
@Override
public boolean saveUserAndSalt(User user) {
//获取从页面传入的角色id,因为salt是在后台生成,所有由salt属性传入角色id的集合
String roleIds = user.getSalt();
//生成随机码作为salt
String salt = UUID.randomUUID().toString();
//获取明文密码
String message = user.getPassword();
//获取密文密码
String encryption = ShiroUtil.encryptionBySalt(salt, message);
//设置user的密码属性
user.setPassword(encryption);
//设置user对象的盐值属性
user.setSalt(salt);
//将用户保存到数据库
Integer insert = userDao.insert(user);
//如果插入成功,并且页面传入的角色id不为空
return updateRoleUser(user,roleIds);
}
@Override
public boolean updateUserAndSalt(User user) {
String roleIds = user.getSalt();
//将用户保存到数据库
Integer update = userDao.updateUserColumById(user);
//如果插入成功,并且页面传入的角色id不为空
if(update>0){
boolean b = updateRoleUser(user, roleIds);
if(b){
return true;
}
}
return false;
}
@Override
public boolean resetPassword(User user) {
//生成随机码作为salt
String salt = UUID.randomUUID().toString();
//获取明文密码
String message = user.getPassword();
//获取密文密码
String encryption = ShiroUtil.encryptionBySalt(salt, message);
//设置user的密码属性
user.setPassword(encryption);
//设置user对象的盐值属性
user.setSalt(salt);
//将用户保存到数据库
Integer reset = userDao.resetPassword(user);
if(reset>0){
return true;
}
return false;
}
/**
* @create by: Teacher陈
* @description: 更新用户和角色中间表
* @create time: 2020/7/19 13:37
*/
private boolean updateRoleUser(User user,String roleIds) {
if ( roleIds != null) {
//删除此用户原有的角色
Wrapper<UserRole> wrapper = new EntityWrapper();
wrapper.eq("user_id", user.getUserId());
userRoleDao.delete(wrapper);
//添加此用户关联的新角色
String[] strings = roleIds.split(",");
for (String string : strings) {
if (string != null && string != "") {
Integer roleID = Integer.parseInt(string);
UserRole userRole = new UserRole();
userRole.setUserId(user.getUserId());
userRole.setRoleId(roleID);
userRoleDao.insert(userRole);
}
}
return true;
}
return false;
}
}
controller:
package com.aaa.controller;
import com.aaa.aop.SaveOrUpdateEntityAnn;
import com.aaa.entity.*;
import com.aaa.service.DeptService;
import com.aaa.service.RoleService;
import com.aaa.service.UserService;
import com.aaa.util.MyConstants;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 用户信息表 前端控制器
* </p>
*
* @author AAATeacherChen
* @since 2020-07-09
*/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
@Autowired
UserService userService;
@Autowired
DeptService deptService;
@Autowired
RoleService roleService;
@RequestMapping("/toShowUser")
public String toShowUser(Model model){
//查询所有的部门信息,填充到页面下拉框中
List<Dept> deptList = deptService.selectList(null);
//查询所有的角色信息,填充到页面下拉框中
List<Role> roleList = roleService.selectList(null);
model.addAttribute("deptList", deptList);
model.addAttribute("roleList", roleList);
return "user/showUser";
}
/**
* create by: Teacher陈
* description: 返回所有的用户信息,包含部门信息
* create time: 2020/7/20 17:20
*
* @Param:
* @return java.lang.String
*/
@RequestMapping("/selectAllUser")
@ResponseBody
public LayUiTable selectAllUser(HttpSession session,Integer page, Integer limit, String searchLoginName, String searchUserName, String searchPhonenumber){
/* int sessionTimeout = session.getServletContext().getSessionTimeout();
System.out.println(sessionTimeout);
long timeout = SecurityUtils.getSubject().getSession().getTimeout();
System.out.println(timeout);*/
LayUiTable table = new LayUiTable();
//多条件查询所需要的集合
Map<String ,Object> condition= new HashMap(16);
Wrapper wrapper = new EntityWrapper();
//添加模糊查询的条件
if (null != searchLoginName && !"".equals(searchLoginName)) {
wrapper.like("login_name", searchLoginName);
condition.put("login_name", searchLoginName);
}
if (null != searchUserName && !"".equals(searchUserName)) {
condition.put("user_name", searchUserName);
}
if (null != searchPhonenumber && !"".equals(searchPhonenumber)) {
condition.put("phonenumber", searchPhonenumber);
}
wrapper.eq("del_flag", 0);
condition.put("del_flag", 0);
int userListCount = userService.selectCount(wrapper);
//如果表中没有数据。则不进行分页查询
if(userListCount>0){
//获取当前的系统毫秒数
long start = System.currentTimeMillis();
Page<UserVo> pageInfo = new Page(page, limit);
List<UserVo> userVoList = userService.selectUserVoList(pageInfo,condition);
//从分页结果中提取list集合
table.setCode(MyConstants.OPERATION_SUCCESS_CODE);
table.setMsg(MyConstants.OPERATION_SUCCESS_MESSAGE);
table.setData(userVoList);
table.setCount(userListCount);
long end = System.currentTimeMillis();
/* System.out.println("============查询花费时间:"+(end-start)+"============");*/
}
return table;
}
/**
* create by: Teacher陈
* description: 判断用户名是否存在,存在的话返回false,不存在返回true ,检验添加用户是否重复
* create time: 2020/7/22 17:08
* @Param: username
* @return boolean
*/
@RequestMapping("/checkUserName")
@ResponseBody
public Result checkUserName(String username){
Wrapper<User> wrapper = new EntityWrapper<>();
User user = userService.selectOne(wrapper.eq("login_name", username));
if (user != null) {
return super.error(MyConstants.OPERATION_FAIL_CODE, username+"已经被占用");
}
return super.success();
}
/**
* create by: Teacher陈
* description: 保存用户
* create time: 2020/7/23 15:43
*
* @return a
* @Param: null
*/
@RequestMapping("/saveUser")
@ResponseBody
@SaveOrUpdateEntityAnn(entityClass = User.class)
public Result saveUser(User user){
boolean insert = userService.saveUserAndSalt(user);
if(insert){
return success();
}
return error();
}
@RequestMapping("/updateUser")
@ResponseBody
@SaveOrUpdateEntityAnn(entityClass = User.class)
/**
* @create by: Teacher陈
* @description: 修改用户
* @create time: 2020/7/18 19:32
* @param user
* @return com.aaa.entity.Result
*/
public Result updateUser(User user){
boolean update = userService.updateUserAndSalt(user);
if(update){
return success();
}
return error();
}
/**
* @create by: Teacher陈
* @description: 删除用户(逻辑删除)
* @create time: 2020/7/19 13:44
*/
@RequestMapping("/deleteUser")
@ResponseBody
public Result deleteUser(User user){
user.setDelFlag("1");
boolean update = userService.updateById(user);
if(update){
return success();
}
return error();
}
/**
* @create by: Teacher陈
* @description: 根据用户id查询自己的角色
* @create time: 2020/7/18 21:28
*/
@RequestMapping("/getRoleCheckByUserId")
@ResponseBody
public Result getRoleCheckByUserId(Integer userId){
List<Role> roleUserList = roleService.selectListByUserId(userId);
List<Role> roleList = roleService.selectList(null);
Map map = new HashMap();
for (Role role : roleList) {
//判断集合包含对象,必须重写equals和hashcode方法
if(roleUserList.contains(role)){
map.put(role.getRoleKey(), true);
}else {
map.put(role.getRoleKey(), false);
}
}
System.out.println(map.toString());
return success(map);
}
/**
* @create by: Teacher陈
* @description: 重置密码
* @create time: 2020/7/19 15:16
*/
@RequestMapping("/resetPassword")
@ResponseBody
public Result resetPassword(User user){
boolean update = userService.resetPassword(user);
if(update){
return success();
}
return error();
}
/**
* @create by: Teacher陈
* @description: 批量删除用户
* @create time: 2020/7/19 15:20
* @param userList
* @return Result
*/
@RequestMapping(value = "/deleteBatchUser")
@ResponseBody
public Result deleteBatchUser(@RequestBody List<User> userList) {
List<User> userListNew = new ArrayList<>();
//此处是逻辑删除,修改delflag
for (User user : userList) {
User userNew = new User();
userNew.setDelFlag("1");
userNew.setUserId(user.getUserId());
userListNew.add(userNew);
}
boolean update = userService.updateBatchById(userListNew);
if (update) {
return super.success();
} else {
return super.error();
}
}
/**
* 去用户基本信息
* @param model
* @param request
* @return
*/
@RequestMapping("toUserInfo")
public String toUserInfo(Model model, HttpServletRequest request) {
//获取session的userid
String remoteUser = request.getRemoteUser();
String[] split = remoteUser.split(",");
String[] split1 = split[0].split("=");
String id = split1[1];
//转integer类型
Integer userId = Integer.valueOf(id);
//根据id查询user列表
User user = userService.selectById(userId);
//获取deptid
Integer deptId = user.getDeptId();
Dept dept = deptService.selectById(deptId);
//获取roleid
// UserController userController = new UserController();
// Result roleCheckByUserId = userController.getRoleCheckByUserId(userId);
// model.addAttribute("role", roleCheckByUserId);
//查询所有的部门信息,填充到页面下拉框中
List<Dept> deptList = deptService.selectList(null);
//查询所有的角色信息,填充到页面下拉框中
List<Role> roleList = roleService.selectList(null);
model.addAttribute("user", user);
model.addAttribute("dept", dept);
model.addAttribute("deptList", deptList);
// model.addAttribute("roleList", roleList);
return "/user/userinfo";
}
/**
* 修改基本信息
* @param user
* @return
*/
@RequestMapping("/updateInfo")
@ResponseBody
@SaveOrUpdateEntityAnn(entityClass = User.class)
public Result update(User user){
user.setPassword(null);
boolean update = userService.updateById(user);
if(update){
return success();
}
return error();
}
/**
* 去修改用户基本信息
* @param model
* @param request
* @return
*/
@RequestMapping("toUpdateUser")
public String toUpdateUser(Model model, HttpServletRequest request) {
//获取session的userid
String remoteUser = request.getRemoteUser();
String[] split = remoteUser.split(",");
String[] split1 = split[0].split("=");
String id = split1[1];
Integer userId = Integer.valueOf(id);
User user = userService.selectById(userId);
Integer deptId = user.getDeptId();
//根据id获取部门信息
Dept dept = deptService.selectById(deptId);
//查询所有的部门信息,填充到页面下拉框中
List<Dept> deptList = deptService.selectList(null);
//查询所有的角色信息,填充到页面下拉框中
List<Role> roleList = roleService.selectList(null);
model.addAttribute("user", user);
model.addAttribute("dept", dept);
model.addAttribute("deptList", deptList);
return "/user/userinfoUpdate";
}
/**
* 去修改用户密码
* @return
*/
@RequestMapping("toPassUser")
public String toPasswordUser() {
return "user/userinfoPassW";
}
/**
* 修改个人密码
* @param user
* @param request
* @return
*/
@RequestMapping("/PasswordUser")
@ResponseBody
public Result PasswordUser(User user,HttpServletRequest request){
//获取session的userid
String remoteUser = request.getRemoteUser();
String[] split = remoteUser.split(",");
String[] split1 = split[0].split("=");
String id = split1[1];
Integer userId = Integer.valueOf(id);
//将id传入user中
user.setUserId(userId);
boolean update = userService.resetPassword(user);
if(update){
return success();
}
return error();
}
}
UserDao.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aaa.dao.UserDao" >
<!--<cache type="com.aaa.redis.MybatisCache" eviction="LRU"></cache>-->
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.aaa.entity.User">
<id column="user_id" property="userId" />
<result column="dept_id" property="deptId" />
<result column="login_name" property="loginName" />
<result column="user_name" property="userName" />
<result column="email" property="email" />
<result column="phonenumber" property="phonenumber" />
<result column="sex" property="sex" />
<result column="avatar" property="avatar" />
<result column="password" property="password" />
<result column="salt" property="salt" />
<result column="status" property="status" />
<result column="del_flag" property="delFlag" />
<result column="create_by" property="createBy" />
<result column="create_time" property="createTime" />
<result column="update_by" property="updateBy" />
<result column="update_time" property="updateTime" />
<result column="remark" property="remark" />
</resultMap>
<!-- 通用查询映射结果 -->
<resultMap id="UserDeptResultMap" type="com.aaa.entity.UserVo">
<id column="user_id" property="userId" />
<result column="dept_id" property="deptId" />
<result column="login_name" property="loginName" />
<result column="user_name" property="userName" />
<result column="email" property="email" />
<result column="phonenumber" property="phonenumber" />
<result column="sex" property="sex" />
<result column="avatar" property="avatar" />
<result column="password" property="password" />
<result column="salt" property="salt" />
<result column="status" property="status" />
<result column="del_flag" property="delFlag" />
<result column="create_by" property="createBy" />
<result column="create_time" property="createTime" />
<result column="update_by" property="updateBy" />
<result column="update_time" property="updateTime" />
<result column="remark" property="remark" />
<association property="dept" column="dept_id" javaType="com.aaa.entity.Dept">
<result column="dept_name" property="deptName"></result>
</association>
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
user_id AS userId, dept_id AS deptId, login_name AS loginName, user_name AS userName, email, phonenumber, sex, avatar, password, salt, status, del_flag AS delFlag, create_by AS createBy, create_time AS createTime, update_by AS updateBy, update_time AS updateTime, remark
</sql>
<!-- 更新用户表的部分列-->
<update id="updateUserColumById" parameterType="com.aaa.entity.User">
update tbl_user set
user_name=#{userName},
dept_id=#{deptId},
email=#{email},
phonenumber=#{phonenumber},
sex=#{sex},
avatar=#{avatar},
status=#{status},
update_by=#{updateBy},
update_time=#{updateTime},
remark=#{remark}
where user_id=#{userId}
</update>
<!-- 重置密码-->
<update id="resetPassword" parameterType="com.aaa.entity.User">
update tbl_user
set password=#{password},
salt=#{salt}
where user_id=#{userId}
</update>
<!--多条件查询-->
<select id="selectUserVoList" resultMap="UserDeptResultMap">
select u.*,d.dept_name from tbl_user u INNER JOIN tbl_dept d on u.dept_id=d.dept_id
<where>
<if test="condition.login_name != null and condition.login_name != ''">
AND u.login_name like concat('%', #{condition.login_name},'%')
</if>
<if test="condition.user_name != null and condition.user_name != ''">
AND u.user_name like concat('%', #{condition.user_name},'%')
</if>
<if test="condition.phonenumber != null and condition.phonenumber != ''">
AND u.phonenumber like concat('%', #{condition.phonenumber},'%')
</if>
<if test="condition.del_flag != null ">
AND u.del_flag = #{condition.del_flag}
</if>
</where>
</select>
</mapper>
lay ui:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>用户管理页面</title>
<link rel="stylesheet" th:href="@{/layui/css/layui.css}">
<script th:src="@{/layui/layui.js}"></script>
</head>
<body>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="resetPassword">重置密码</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete"
shiro:hasPermission="system:user:remove">删除</a>
<!--<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete" >删除</a>-->
</script>
<form class="layui-form" action="" id="save_user_form" style="display: none">
<div class="layui-form-item">
<label class="layui-form-label">登录名</label>
<div class="layui-input-block">
<input type="text" name="loginName" id="loginName" required lay-verify="required" placeholder="请输入登录名称"
autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密 码</label>
<div class="layui-input-block">
<input type="text" name="password" required lay-verify="required" placeholder="请设置密码" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">真实姓名</label>
<div class="layui-input-inline">
<input type="text" name="userName" required lay-verify="required" placeholder="请输入真实姓名" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">邮箱</label>
<div class="layui-input-inline">
<input type="text" name="email" required lay-verify="email" placeholder="请输入电子邮箱" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">手机号</label>
<div class="layui-input-inline">
<input type="text" name="phonenumber" required lay-verify="required|phone" placeholder="请输入手机号"
autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">部门</label>
<div class="layui-input-block">
<select name="deptId" lay-verify="required">
<option th:each="dept:${deptList}" th:value="${dept.deptId}" th:text="${dept.deptName}"></option>
</select>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">状态</label>
<div class="layui-input-block">
<input type="checkbox" name="status" lay-skin="switch" lay-text="正常|禁用" checked value="0">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="radio" name="sex" value="0" title="男" checked="">
<input type="radio" name="sex" value="1" title="女">
</div>
</div>
</div>
<div class="layui-form-item" pane="">
<label class="layui-form-label">角色</label>
<div class="layui-input-block">
<input th:each="role:${roleList}" name="role" type="checkbox" th:value="${role.roleId}"
lay-skin="primary"
th:text="${role.roleName}">
</div>
<input hidden="hidden" name="salt">
</div>
<div class="layui-form-item">
<label class="layui-form-label">备注</label>
<div class="layui-input-inline">
<input type="text" name="remark" required lay-verify="required" placeholder="请输入备注信息" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<!--===========================================更新用户信息==============================================================-->
<form class="layui-form" action="" id="update_user_form" style="display: none" lay-filter="update_user_form">
<!--隐藏输入框,保存主键-->
<div style="margin-top: 2%"></div>
<input type="hidden" name="userId">
<input type="hidden" name="loginName">
<input type="hidden" name="password">
<div class="layui-form-item">
<label class="layui-form-label">真实姓名</label>
<div class="layui-input-inline">
<input type="text" name="userName" required lay-verify="required" placeholder="请输入真实姓名" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">邮箱</label>
<div class="layui-input-inline">
<input type="text" name="email" required lay-verify="email" placeholder="请输入电子邮箱" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">手机号</label>
<div class="layui-input-inline">
<input type="text" name="phonenumber" required lay-verify="required|phone" placeholder="请输入手机号"
autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">部门</label>
<div class="layui-input-block">
<select name="deptId" lay-verify="required">
<option th:each="dept:${deptList}" th:value="${dept.deptId}" th:text="${dept.deptName}"></option>
</select>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">状态</label>
<div class="layui-input-block">
<input type="checkbox" name="status" lay-skin="switch" lay-text="正常|禁用" checked value="0">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="radio" name="sex" value="0" title="男" checked="">
<input type="radio" name="sex" value="1" title="女">
</div>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">角色</label>
<div class="layui-input-block">
<input class="role_check" th:each="role:${roleList}" th:name="${role.roleKey}" type="checkbox"
th:value="${role.roleId}"
lay-skin="primary" th:text="${role.roleName}">
</div>
<input hidden="hidden" name="salt">
</div>
<div class="layui-form-item">
<label class="layui-form-label">备注</label>
<div class="layui-input-inline">
<input type="text" name="remark" required lay-verify="required" placeholder="请输入备注信息" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formUpdateUser">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<!--=========================================重置密码===============================-->
<form class="layui-form" action="" id="reset_password_form" style="display: none" lay-filter="reset_password_form">
<!--隐藏输入框,保存主键-->
<input type="hidden" name="userId">
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-inline">
<input type="text" name="password" required lay-verify="required" placeholder="请输入新密码" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formResetPassword-flter">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<div class="layui-fluid">
<!--=============================条件查询==================================-->
<div class="layui-card" style="padding-top: 30px">
<form class="layui-form">
<div class="layui-inline">
<label class="layui-form-label">登录名</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" id="searchLoginName" name="searchLoginName" placeholder="登录名"
width="80px">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">真实姓名</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" id="searchUserName" name="searchUserName"
placeholder="真实姓名"
width="80px">
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">手机号</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" id="searchPhonenumber" name="searchPhonenumber"
placeholder="手机号"
width="80px">
</div>
</div>
<div class="layui-inline">
<button class="layui-btn" lay-submit="search_submits" lay-filter="search_filter">查询</button>
<button id="search_reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</form>
</div>
<div class="layui-card">
<table id="demo" lay-filter="userTable"></table>
</div>
</div>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="addUser">添加</button>
<button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="deleteBatch">删除</button>
</div>
</script>
</body>
<script>
layui.use(['layer', 'form', 'table', 'jquery'], function () {
var table = layui.table;
var form = layui.form;
var $ = layui.jquery;
//第一个实例
var myTable = table.render({
elem: '#demo'
, id: 'tableReload'//重载数据表格
, height: 420
, url: '/user/selectAllUser' //数据接口
, page: true //开启分页
, limit: 5//默认一页显示5条数据
, limits: [5, 10, 15, 20, 50, 100]//默认一页显示5条数据
, toolbar: '#toolbarDemo'//此处的id是html代码段
, cols: [
[ //表头
{field: 'userId', title: '用户编号', sort: true, fixed: 'left', checkbox: true}
, {field: 'userId', title: '编号', sort: true, width: '7%',}
, {field: 'loginName', title: '登录名', width: '9%',}
, {field: 'userName', title: '真实姓名', width: '7%',}
, {field: 'phonenumber', title: '手机号'}
, {
field: 'sex', title: '性别', width: '6%',
templet: function (d) {
if (d.sex == 0) {
return "男"
} else {
return "女"
}
}
}
, {
field: 'status', title: '状态', width: '6%',
templet: function (d) {
if (d.status == 0) {
return '<button type="button" class="layui-btn layui-btn-xs">正常</button>'
} else {
return '<button type="button" class="layui-btn layui-btn-xs layui-btn-danger">禁用</button>'
}
}
}
, {
field: 'deptName', title: '部门名称', width: '8%',
templet: function (d) {
return d.dept.deptName
}
}
, {field: 'createTime', title: '创建时间'}
, {field: 'updateBy', title: '修改人', hide: true}
, {field: 'updateTime', title: '修改时间', hide: true}
, {field: 'remark', title: '备注', hide: true}
, {title: '操作', width: 235, toolbar: '#barDemo'}
]]
});
//监听头工具栏事件
table.on('toolbar(userTable)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id)
, data = checkStatus.data; //获取选中的数据
switch (obj.event) {
case 'addUser':
layer.open({
title: '添加员工',
type: 1,
content: $('#save_user_form'),
area: ['700px', '530px']
});
break;
case 'update':
if (data.length === 0) {
layer.msg('请选择一行');
} else if (data.length > 1) {
layer.msg('只能同时编辑一个');
} else {
layer.alert('编辑 [id]:' + checkStatus.data[0].id);
}
break;
case 'deleteBatch':
if (data.length === 0) {
layer.msg('请选择一行');
} else {
//对于删除或者是其他敏感操作,一定要让用户确认。
layer.confirm('确定要删除吗?', function () {
//请求后台批量删除接口
$.ajax({
url: '/user/deleteBatchUser',
dataType: 'json',
contentType: "application/json;charset=UTF-8",
type: 'POST',
data: JSON.stringify(data),//将js对象转成json串传入到后台
success: function (result) {
layer.closeAll();//关闭对话框
layer.msg(result.msg);
myTable.reload();//重新加载表格数据
}
})
})
}
break;
}
;
});
//监听保存用户表单的提交
form.on('submit(formDemo)', function (data) {
data.field.status = data.field.status ? 0 : 1;
var checkeds = selectCheckeds("role");
//盐值在添加的时候没有用处,所以将角色信息放入到盐值中传入后端
data.field.salt = checkeds;
console.log(checkeds);
$.ajax({
url: '/user/saveUser',
dataType: 'json',
type: 'POST',
data: data.field,
success: function (result) {
layer.closeAll();//关闭对话框
layer.msg(result.msg);
myTable.reload();//重新加载表格数据
}
})
return false;
});
//监听修改用户表单的提交
form.on('submit(formUpdateUser)', function (data) {
data.field.status = data.field.status ? 0 : 1;
var checkeds = selectCheckeds();
//盐值在添加的时候没有用处,所以将角色信息放入到盐值中传入后端
data.field.salt = checkeds;
$.ajax({
url: '/user/updateUser',
dataType: 'json',
type: 'POST',
data: data.field,
success: function (result) {
layer.closeAll();//关闭对话框
layer.msg(result.msg);
myTable.reload();//重新加载表格数据
}
})
return false;
});
//登录名校验
$("#loginName").blur(function () {
var node = this;
console.log(node)
$.ajax({
type: "POST",
url: "/user/checkUserName",
async: false, //改为同步请求
data: {username: node.value},
dataType: 'json',
success: function (data) {
if (data.code == 0) {
} else {
node.focus();
layer.msg(data.msg, {icon: 5});
}
}
});
});
// 获取选中复选框项
function selectCheckeds(name) {
var checkeds = "";
// 保存用户
if (name != null) {
$('input:checkbox[name="' + name + '"]:checked').each(function (i) {
if (0 == i) {
checkeds = $(this).val();
} else {
checkeds += ("," + $(this).val());
}
});
//修改用户
} else {
$('.role_check:checked').each(function (i) {
if (0 == i) {
checkeds = $(this).val();
} else {
checkeds += ("," + $(this).val());
}
});
}
return checkeds;
}
//监听查询表单的提交事件
form.on('submit(search_filter)', function (data) {
var formData = data.field;
//数据表格重载
table.reload('tableReload', {
page: {
curr: 1 //重新从第 1 页开始
}
, where: {//这里传参 向后台
searchLoginName: formData.searchLoginName,
searchUserName: formData.searchUserName,
searchPhonenumber: formData.searchPhonenumber
}
});
return false;//false:阻止表单跳转 true:表单跳转
});
//监听重置密码表单的提交事件
form.on('submit(formResetPassword-flter)', function (data) {
$.ajax({
url: '/user/resetPassword',
dataType: 'json',
type: 'POST',
data: data.field,
success: function (result) {
layer.closeAll();//关闭对话框
layer.msg(result.msg);
}
})
return false;
});
//监听行工具事件
table.on('tool(userTable)', function (obj) { //注:tool 是工具条事件名,userTable 是 table 原始容器的属性 lay-filter="对应的值"
var data = obj.data //获得当前行数据
var layEvent = obj.event; //获得 lay-event 对应的值
if (layEvent === 'detail') {
layer.msg('查看操作');
} else if (layEvent === 'delete') {
layer.confirm('真的删除行么', function (index) {
/* obj.del(); //删除对应行(tr)的DOM结构
layer.close(index);*/
//向服务端发送删除指令
console.log(data);
$.ajax({
url: '/user/deleteUser',
dataType: 'json',
type: 'POST',
data: {userId: data.userId},
success: function (result) {
layer.closeAll();//关闭对话框
layer.msg(result.msg);
myTable.reload();//重新加载表格数据
}
})
});
} else if (layEvent === 'resetPassword') {
form.val('reset_password_form', {
"userId": data.userId});
layer.open({
title: '重置密码',
type: 1,
content: $('#reset_password_form'),
area: ['400px', '150px']
});
} else if (layEvent === 'edit') {
//将修改前的数据赋值给修改表单
form.val('update_user_form', {
"userId": data.userId
, "loginName": data.loginName // "name": "value"
, "password": data.orderNum
, "userName": data.userName
, "email": data.email
, "phonenumber": data.phonenumber
, "deptId": data.deptId
, "status": data.status == 0 ? true : false //开关状态
, "sex": data.sex
, "remark": data.remark
});
//设置checkbox回显
$.ajax({
url: '/user/getRoleCheckByUserId',
dataType: 'json',
type: 'POST',
data: {userId: data.userId},
success: function (result) {
console.log(result.data)
form.val('update_user_form', result.data);
}
});
layer.open({
title: '编辑用户',
type: 1,
content: $('#update_user_form'),
area: ['500px', '480px']
});
}
});
//点击重置按钮,清除查询关键字,并且重新加载表格数据
$("#search_reset").on("click",function () {
$("#searchLoginName").val=null;
$("#searchUserName").val=null;
$("#searchPhonenumber").val=null;
myTable.reload();//重新加载表格数据
})
});
</script>
</html>
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/teacher?characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
#spring.datasource.password=203786
spring.datasource.password=123456
#mybatis.mapper-locations=classpath:mapper/*.xml
mybatis-plus.mapper-locations=classpath:mapper/*.xml
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#\u65E5\u5FD7 debug info warn error feta
logging.level.com.aaa.dao=debug
#\u5F00\u542Fmybatisplus\u7684\u4E8C\u7EA7\u7F13\u5B58
#mybatis-plus.configuration.cache-enabled=true
#redis\u670D\u52A1\u5668\u7684IP\u5730\u5740
spring.redis.host=192.168.11.100
#redis\u7684\u7AEF\u53E3\u53F7
##spring.redis.port=6379
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB