显示角色列表下的用户列表
前端
效果图
html页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户管理</title>
<jsp:include page="/common/backend_common.jsp"/>
<jsp:include page="/common/page.jsp"/>
<jsp:include page="/template/permission/roleListTemplate2.jsp"/>
<jsp:include page="/template/permission/userListTemplate.jsp"/>
<jsp:include page="userForm/userForm.jsp"/>
</head>
<body class="no-skin" style="background: white">
<!-- 内容 -->
<div class="main-content">
<div class="main-content-inner">
<!-- 导航路径 -->
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="/sys/admin/index.page">Home</a>
</li>
<li class="">权限管理</li>
<li class="">角色管理</li>
</ul><!-- /.breadcrumb -->
<div class="nav-search" id="nav-search">
<form class="form-search">
<span class="input-icon">
<input type="text" placeholder="Search ..." class="nav-search-input" id="nav-search-input" autocomplete="off" />
<i class="ace-icon fa fa-search nav-search-icon"></i>
</span>
<a href="#">
<span class="menu-icon fa fa-shopping-cart" style="margin-left: 30px; color: coral; font-size: 30px"></span>
</a>
</form>
</div>
</div>
<div class="page-content">
<div class="page-header">
<h1>用户管理
<small>
<i class="ace-icon fa fa-angle-double-right"></i>
用户列表
</small>
</h1>
</div><!-- /.page-header -->
<div class="row">
<div class="col-xs-12">
<div class="col-sm-3">
<div class="table-header">
角色列表 <a class="green" href="#"></a>
</div>
<!-- 读取角色 -->
<div id="roleList"></div>
</div>
<div class="col-xs-9">
<!-- <ul class="list-inline fa-border">
<li><button type="button" class="btn btn-warning fa fa-plus user-add">添加用户</button></li>
</ul>-->
<div class="col-xs-12 fa-border" >
<ul class="list-inline">
<li>展示 <select id="pageSize">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select> 条记录</li>
<li><input type="search" id="keyword" name="keyword" placeholder="关键字"/></li>
<li>状态 <select id="search_status">
<option value="1">有效</option>
<option value="0">无效</option>
</select></li>
<li><button class="btn btn-info fa fa-check research">查询</button></li>
</ul><!--/.ul-->
<table id="simple-table" class="table table-bordered table-hover">
<thead>
<tr>
<th>用户名</th>
<th>所属角色</th>
<th>手机号</th>
<th>邮箱</th>
<th>创建时间</th>
<th>更新时间</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody id="userList"></tbody>
</table>
<div class="row" id="userPage"></div>
</div>
</div>
</div>
</div><!-- /.row -->
</div><!-- /.page-content -->
</div><!-- /.main-content-inner -->
</div><!-- /.main-content -->
<!-- 引入js文件-->
<script src="/js/permission/user.js"></script>
</body>
</html>
分页
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<script id="paginateTemplate" type="x-tmpl-mustache">
<div class="col-xs-6">
<div class="dataTables_info" id="dynamic-table_info" role="status" aria-live="polite">
总共 {{total}} 条中的 {{from}} ~ {{to}}条 当前第{{pageNo}}页 共 {{maxPageNo}}页
</div>
</div>
<div class="col-xs-6">
<div class="dataTables_paginate paging_simple_numbers" id="dynamic-table_paginate">
<ul class="pagination">
<li class="paginate_button previous {{^firstUrl}}disabled{{/firstUrl}}" aria-controls="dynamic-table" tabindex="0">
<a href="#" data-target="1" data-url="{{firstUrl}}" class="page-action">首页</a>
</li>
<li class="paginate_button {{^beforeUrl}}disabled{{/beforeUrl}}" aria-controls="dynamic-table" tabindex="0">
<a href="#" name="前一页" data-target="{{beforePageNo}}" data-url="{{beforeUrl}}" class="page-action">前一页</a>
</li>
<li class="paginate_button active" aria-controls="dynamic-table" tabindex="0">
<a href="#" data-id="{{pageNo}}" >第{{pageNo}}页</a>
<input type="hidden" class="pageNo" value="{{pageNo}}" />
</li>
<li class="paginate_button {{^nextUrl}}disabled{{/nextUrl}}" aria-controls="dynamic-table" tabindex="0">
<a href="#" name="后一页" data-target="{{nextPageNo}}" data-url="{{nextUrl}}" class="page-action">后一页</a>
</li>
<li class="paginate_button next {{^lastUrl}}disabled{{/lastUrl}}" aria-controls="dynamic-table" tabindex="0">
<a href="#" data-target="{{maxPageNo}}" data-url="{{lastUrl}}" class="page-action">尾页</a>
</li>
<li class="paginate_button {{^skipUrl}}disabled{{/skipUrl}}" aria-controls="dynamic-table" tabindex="0">
<input class="skiptxt" style="width:50px;float:left;background:lightgray;border:1px solid orange;" type="number" value="{{skipNo}}"/>
<a href="#" data-target="{{pageNo}}" data-url="{{skipUrl}}" class="page-action skip">跳转</a>
</li>
</ul>
</div>
</div>
</script>
<!-- 不要求会写,但是希望你掌握-->
<script type="text/javascript">
//01找到模板中的内容,把html中的数据封装到js自定义的变量中
//paginationTemplate 分页模板的英文,自定义名字
var paginateTemplate = $("#paginateTemplate").html();
//02将页面变量内容交给mustache库,使用mustache技术加载指定模板
Mustache.parse(paginateTemplate);
//渲染分页的内容
//url total pageNo pageSize currentSize idElement:将paginatetemplate加载到哪一个页面版块 预留一个回调函数
function renderPage(url, total, pageNo, pageSize, currentSize, idElement,
callback) {
//得到最大的页码,使用向上取整的函数
var maxPageNo = Math.ceil(total / pageSize);
//url: /order/page.json?username=apple&age=100
var paramStartChar = url.indexOf("?") > 0 ? "&" : "?";
//数据从哪里开始
var from = (pageNo - 1) * pageSize + 1;
//处理当前页为数字类型
var pageNo = parseInt(pageNo);
var skipNo=pageNo;
//定义视图内容[1][2]当前页[前一页][后一页]...
var view = {
from : from > total ? total : from,
to : (from + currentSize - 1) > total ? total
: (from + currentSize - 1),
total : total,
pageNo : pageNo,
skipNo:pageNo,
maxPageNo : maxPageNo,
nextPageNo : pageNo >= maxPageNo ? maxPageNo : (pageNo + 1),
beforePageNo : pageNo == 1 ? 1 : (pageNo - 1),
firstUrl : (pageNo == 1) ? '' : (url + paramStartChar
+ "pageNo=1&pageSize=" + pageSize),
beforeUrl : (pageNo == 1) ? '' : (url + paramStartChar + "pageNo="
+ (pageNo - 1) + "&pageSize=" + pageSize),
nextUrl : (pageNo >= maxPageNo) ? '' : (url + paramStartChar
+ "pageNo=" + (pageNo + 1) + "&pageSize=" + pageSize),
lastUrl : (pageNo >= maxPageNo) ? '' : (url + paramStartChar
+ "pageNo=" + maxPageNo + "&pageSize=" + pageSize),
skipUrl : url + paramStartChar + "pageNo=" + skipNo + "&pageSize="
+ pageSize
};
//idElement="orderPage"
//找到页面中的<div class="row" id="orderPage"></div>
//Mustache.render(paginateTemplate, view) 使用mustache模板,对指定模板进行数据填充
$("#" + idElement).html(Mustache.render(paginateTemplate, view));
//每一个页码按钮拥有一个点击事件
$(".page-action").click(function(e) {
//阻止默认事件,冒泡
e.preventDefault();
//获取当前的skipno
var skipNo = $(".skiptxt").val();
if (skipNo != null && skipNo > 0) {
pageNo = parseInt(skipNo>=maxPageNo?maxPageNo:skipNo);
$(".skip").attr("data-target",pageNo).attr(//
"data-url",//
url + paramStartChar + "pageNo=" + pageNo
+ "&pageSize=" + pageSize);
}
var targetUrl = $(this).attr("data-url");
//给每一个按钮添加指定的值
$("#" + idElement + " .pageNo").val(
$(this).attr("data-target"));
//填充每一个按钮上的url
//让回调函数执行这个url
if (targetUrl != '') {
$.ajax({
url : targetUrl,
success: function (result) {
callback(result,url)
}
});
//callback(targetUrl);//交由其他地方的ajax请求来传输页码,url以及数据
}
})
}
</script>
模板引擎
roleListTemplate
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script id="roleListTemplate2" type="x-tmpl-mustache">
<ul class="dd-list">
{{#roleList}}
<li class="dd-item dd2-item role-name" id="role_{{id}}" href="javascript:void(0)" data-id="{{id}}">
<div class="dd2-content" style="cursor:pointer;">{{name}}</div>
</li>
{{/roleList}}
</ul>
</script>
userListTemplate
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script id="userListTemplate" type="x-tmpl-mustache">
{{#userList}}
<tr role="row" class="user-name odd" data-id="{{id}}"><!--even -->
<td>{{username}}</td>
<td>{{showRoleId}}</td>
<td>{{telephone}}</td>
<td>{{mail}}</td>
<td>{{#create_time}}{{/create_time}}</td>
<td>{{#update_time}}{{/update_time}}</td>
<td>{{#bold}}{{showStatus}}{{/bold}}</td>
<td>
<div class="hidden-sm hidden-xs action-buttons">
<a class="blue user-edit" href="#" data-id="{{id}}">
<i class="ace-icon fa fa-pencil bigger-100"></i>
</a>
</div>
</td>
</tr>
{{/userList}}
</script>
绑定更新事件的操作模板 userForm
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/3/23 0023
Time: 17:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div id="dialog-user-form" style="display: none;">
<form id="userForm">
<table class="table table-striped table-bordered table-hover dataTable no-footer" role="grid">
<tr>
<td style="width: 80px;"><label for="roleSelectId">所属角色</label></td>
<td><select id="roleSelectId" name="roleId"
data-placeholder="选择角色" style="width: 150px;"></select></td>
</tr>
<tr>
<td><label for="userName" style="width: 60px">用户名</label></td>
<td>
<input type="text" name="username" id="userName" value="" class="text ui-widget-content ui-corner-all">
<input type="hidden" name="id" id="userId"/>
</td>
</tr>
<tr>
<td><label for="userTelephone">电话</label></td>
<td><input type="text" name="telephone" id="userTelephone"
value="" class="text ui-widget-content ui-corner-all"></td>
</tr>
<tr>
<td><label for="userMail">邮箱</label></td>
<td><input type="text" name="mail" id="userMail" value=""
class="text ui-widget-content ui-corner-all"></td>
</tr>
<tr>
<td><label for="userStatus">状态</label></td>
<td>
<select id="userStatus" name="userStatus" data-placeholder="状态" style="width: 150px;">
<option value="1">有效</option>
<option value="0">无效</option>
</select>
</td>
</tr>
</table>
</form>
</div>
js
$(function () {
var roleList; // 存储角色列表
var roleMap = {}; // 存储map格式的角色信息
var userMap = {}; // 存储map格式的用户信息
var pageNo; // 当前页码
var pageSize; // 每页显示条数
var keyword; // 关键字查询
var search_status; // 状态
var optionStr = ""; // 角色标签
var lastClickRoleId = -1; // 最后一次选中角色id
// 使用mustache模板
var roleListTemplate2 = $('#roleListTemplate2').html();
Mustache.parse(roleListTemplate2);
// 用户的mustache模板
var userListTemplate = $('#userListTemplate').html();
Mustache.parse(userListTemplate);
loadRoleList();
// 渲染角色列表
function loadRoleList() {
$.ajax({
url : "/sys/permission/roleList.json",
type : "POST",
success : function (result) {
// 如果返回成功
if (result.status == "success"){
// 渲染视图
var rendered = Mustache.render(roleListTemplate2 , {
"roleList" : result.data
});
roleList = result.data;
// 将每一个角色添加到map中
$.each(result.data, function (i, role) {
roleMap[role.id] = role;
});
// 在指定id下填充数据页面样式
$('#roleList').html(rendered);
// 绑定操作
bindRoleClick();
}else {
showMessage("加载角色列表", result.msg, false);
}
}
});
}
// 绑定角色操作
function bindRoleClick() {
$('.role-name').click(function (e) {
// 阻止默认事件冒泡
e.preventDefault();
e.stopPropagation();
// 获取角色id
var roleId = $(this).attr("data-id");
handleRoleSelected(roleId);
});
}
// 点击角色后的变化
function handleRoleSelected(roleId) {
if (lastClickRoleId != -1){
var lastRole = $("#role_" + lastClickRoleId + " .dd2-content:first");
lastRole.removeClass("btn-yellow");
lastRole.removeClass("no-hover");
}
var currentRole = $("#role_" + roleId + " .dd2-content:first");
currentRole.addClass("btn-yellow");
currentRole.addClass("no-hover");
lastClickRoleId = roleId;
// 渲染用户列表
loadUserList(roleId);
// 查询操作
$('.research').click(function (e) {
// 阻止默认事件
e.preventDefault();
$("#rolePage .pageNo").val(1);
loadUserList(roleId);
});
}
// 渲染用户列表
function loadUserList(roleId) {
// 获取页码和当前页显示条数
pageNo = $('#userPage .pageNo').val() || 1;
pageSize = $('#pageSize').val();
keyword = $('#keyword').val(); // 获取关键字
search_status = $('#search_status').val(); // 获取状态
var url = "/sys/permission/user.json?roleId=" + roleId; // 用户请求资源
$.ajax({
url: url,
type: "POST",
data : {
pageNo : pageNo,
pageSize : pageSize,
keyword : keyword,
search_status : search_status
},
success : function (result) {
renderUserListAndPage(result, url);
}
});
}
// 渲染细节
function renderUserListAndPage(result, url) {
if (result.status == "success"){
if (result.data.total > 0){
var rendered = Mustache.render(userListTemplate, {
"userList" : result.data.records,
"showRoleId" : function () {
return roleMap[this.roleId].name;
},
"create_time" : function () {
return function (text, render){
return new Date(
this.createTime)
.Format("yyyy-MM-dd");
}
},
"update_time" : function() {
return function(text, render) {
return new Date(
this.updateTime)
.Format("yyyy-MM-dd");
}
},
"showStatus" : function() {
return this.userStatus == 1 ? '有效'
: (this.userStatus == 0 ? '无效'
: '删除');
},
"bold" : function() {
return function(text, render) {
var status = render(text);
if (status == '有效') {
return "<span class='label label-sm label-success'>有效</span>";
} else if (status == '无效') {
return "<span class='label label-sm label-warning'>无效</span>";
} else {
return "<span class='label'>删除</span>";
}
}
}
});
// 将user添加到usermap中
$.each(result.data.records, function (i, user) {
userMap[user.id] = user;
});
//在指定id下添加带数据的页面样式
$('#userList').html(rendered);
}else {
$('#userList').html("");
}
// 绑定操作
bindUserClick();
pageNo = $('#userPage .pageNo').val() || 1; // 获取当前页码
pageSize = $('#pageSize').val(); // 获取显示条数
// 分页页码
renderPage(
url,
result.data.total,
pageNo,
pageSize,
result.data.total > 0 ? result.data.records.length : 0,
"userPage",
renderUserListAndPage);
}else {
showMessage("获取角色下的用户列表",result.msg, false);
}
}
// 绑定用户操作
function bindUserClick() {
// 更新用户
$('.user-edit').click(function (e) {
// 阻止事件冒泡
e.preventDefault();
e.stopPropagation();
// 获取用户id
var userId = $(this).attr("data-id");
// 弹出框
$('#dialog-user-form').dialog({
model : true, // 背景不可修改
title : "更新用户",
open : function (event, ui) {
// 隐藏关闭按钮
$('.ui-dialog-titlebar-close', $(this).parent()).hide();
// 角色选择
optionStr = "";
if (roleList && roleList.length > 0){
$.each(roleList, function (i, role) {
optionStr += Mustache.render("<option value='{{id}}'>{{name}}</option>", {id: role.id, name: role.name});
});
}
// 清空表单
$('#userForm')[0].reset();
$('#roleSelectId').html(optionStr);
// 拿到map中的键值对
var targetUser = userMap[userId];
// 如果存在,则取出
if (targetUser){
$('#roleSelectId').val(targetUser.roleId);
$('#userId').val(targetUser.id);
$('#userName').val(targetUser.username)
$('#userTelephone').val(targetUser.telephone);
$('#userMail').val(targetUser.mail);
$('#userStatus').val(targetUser.userStatus);
}
},
buttons : {
"更新" : function (e) {
e.preventDefault();
// 更新用户
$.ajax({
url : "/sys/permission/updateUser.json",
type : "POST",
data : $('#userForm').serializeArray(), // 数据序列化
success : function (result) {
if(result.status == "success"){
showMessage("更新角色",result.msg, true);
// 关闭模态框
$('#dialog-user-form').dialog("close");
// 显示用户列表
loadUserList(lastClickRoleId);
}else {
showMessage("更新角色",result.msg, false);
}
}
});
},
"取消" : function () {
$('#dialog-user-form').dialog("close");
}
}
});
});
}
});
后台
springboot配置mybatis-plus依赖
<!--引入mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
mybatis-plus的配置文件
package com.lzy.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;
@EnableTransactionManagement
@Configuration
@MapperScan("com.lzy.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
返回角色列表
在postman中测试截图
pojo类的配置
package com.lzy.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import java.util.Date;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_role")
public class SysRole{
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String describes;
private Integer status;
private String creator;
private Date createTime;
private Date updateTime;
}
mapper 的配置
package com.lzy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lzy.pojo.SysRole;
public interface SysRoleMapper extends BaseMapper<SysRole> {
}
Controller
// 返回角色列表
@RequestMapping("/roleList.json")
@ResponseBody
public CommonReturnType roleList(){
List<SysRole> result = sysRoleService.roleList();
return CommonReturnType.success(result);
}
service
@Override
public List<SysRole> roleList() {
List<SysRole> roles = sysRoleMapper.selectList(null);
return roles;
}
返回角色下的用户列表
用户的pojo类
package com.lzy.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_user")
public class SysUser {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String salt;
private String telephone;
private String mail;
private Integer roleId;
private Integer userStatus;
private Date createTime;
private Date updateTime;
}
PageQuery
package com.lzy.page;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.validation.constraints.Min;
// 页码查询
@ToString
public class PageQuery {
// 页码
@Getter
@Setter
@Min(value = 1, message = "当前页码不合法")
private Integer pageNo = 1;
// 显示条数
@Getter
@Setter
@Min(value = 1, message = "每页显示条数不合法")
private Integer pageSize = 10;
}
vo 与视图交互的数据
SearhUserVo
package com.lzy.viewobject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class SearchUserVo {
private String keyword;
private String search_status;
}
SysUserVo
package com.lzy.viewobject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class SysUserVo {
// 用户id
private Integer id;
// 角色id
private Integer roleId;
// 用户名
@NotBlank(message = "用户名不能为空")
@Length(max = 15, min = 2, message = "用户名应在2-15个字之间")
private String username;
// 手机号
@NotBlank(message = "手机号不能为空")
private String telephone;
// 邮箱
@NotBlank(message = "邮箱不能为空")
private String mail;
// 状态
private Integer userStatus;
}
dto 与数据库交互数据传输对象
package com.lzy.dto;
import lombok.Data;
@Data
public class SearchUserDto {
private String keyword;
private Integer search_status;
}
用户controller配置
package com.lzy.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lzy.page.PageQuery;
import com.lzy.pojo.SysRole;
import com.lzy.pojo.SysUser;
import com.lzy.response.CommonReturnType;
import com.lzy.service.SysUserService;
import com.lzy.viewobject.SearchUserVo;
import com.lzy.viewobject.SysUserVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/sys/permission")
public class SysUserController {
public static String FPATH = "permission/";
@Resource
private SysUserService sysUserService;
// 返回用户页面
@RequestMapping("/user.page")
public String userPage(){
return FPATH + "user";
}
// 返回用户列表
@RequestMapping("/user.json")
@ResponseBody
public CommonReturnType user(@RequestParam("roleId") int roleId, SearchUserVo userVo, PageQuery pageQuery){
IPage<SysUser> result = sysUserService.userPageByRoleId(roleId, userVo, pageQuery);
return CommonReturnType.success(result);
}
// 更新用户
@RequestMapping("/updateUser.json")
@ResponseBody
public CommonReturnType update(SysUserVo userVo){
sysUserService.updateUser(userVo);
return CommonReturnType.success("success");
}
}
service
package com.lzy.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.lzy.dto.SearchUserDto;
import com.lzy.error.BusinessException;
import com.lzy.mapper.SysUserMapper;
import com.lzy.page.PageQuery;
import com.lzy.pojo.SysUser;
import com.lzy.service.SysUserService;
import com.lzy.validator.ValidatorApi;
import com.lzy.viewobject.SearchUserVo;
import com.lzy.viewobject.SysUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
@Service
public class SysUserServiceImpl implements SysUserService {
@Resource
private ValidatorApi validator;
@Resource
private SysUserMapper sysUserMapper;
// 根据角色id返回用户列表
@Override
public IPage<SysUser> userPageByRoleId(int roleId, SearchUserVo userVo, PageQuery pageQuery) {
// 注解检验
validator.check(pageQuery);
// 将vo赋值给dto
SearchUserDto dto = new SearchUserDto();
if (StringUtils.isNotBlank(userVo.getKeyword())){
dto.setKeyword(userVo.getKeyword());
}
if (StringUtils.isNotBlank(userVo.getSearch_status())){
dto.setSearch_status(Integer.parseInt(userVo.getSearch_status()));
}
// mybatis-plus 的查询条件
QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(String.valueOf(roleId))){
queryWrapper.eq("role_id", roleId);
}
if (StringUtils.isNotBlank(dto.getKeyword())){
// 模糊查询 %name%
queryWrapper.like("username", dto.getKeyword()).or()
.like("telephone", dto.getKeyword()).or()
.like("mail", dto.getKeyword());
}
if (StringUtils.isNotBlank(String.valueOf(dto.getSearch_status()))){
queryWrapper.eq("user_status", dto.getSearch_status());
}
// 统计符合条件的数据
int count = sysUserMapper.selectCount(queryWrapper);
IPage<SysUser> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
if (count > 0){
page = sysUserMapper.selectPage(page,queryWrapper);
return page;
}
return page;
}
// 更新用户
@Override
public void updateUser(SysUserVo userVo) {
// 注解检验
validator.check(userVo);
// 根据id查询用户是否存在
SysUser before = sysUserMapper.selectById(userVo.getId());
Preconditions.checkNotNull(before, "待更新的用户不存在!");
// 手机号去重
if (checkTelephoneExist(userVo.getTelephone(), userVo.getId())){
throw new BusinessException("该手机号已经存在!");
}
// 邮箱去重
if (checkMailExist(userVo.getMail(), userVo.getId())){
throw new BusinessException("该邮箱已经存在!");
}
// 建造者模式
SysUser entity = SysUser.builder().id(userVo.getId()).username(userVo.getUsername())
.roleId(userVo.getRoleId()).telephone(userVo.getTelephone()).mail(userVo.getMail())
.userStatus(userVo.getUserStatus()).updateTime(new Date()).build();
sysUserMapper.updateById(entity);
}
// 手机号去重
private boolean checkTelephoneExist(String tel, Integer id){
QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(tel)){
queryWrapper.eq("telephone", tel);
}
if (StringUtils.isNotBlank(String.valueOf(id))){
queryWrapper.ne("id", id);
}
return sysUserMapper.selectCount(queryWrapper) > 0;
}
// 邮箱去重
private boolean checkMailExist(String mail, Integer id){
QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(mail)){
queryWrapper.eq("mail", mail);
}
if (StringUtils.isNotBlank(String.valueOf(id))){
queryWrapper.ne("id", id);
}
return sysUserMapper.selectCount(queryWrapper) > 0;
}
}
源代码地址:
github : https://github.com/longzy-hub/SuperMarket