十三、后台模块-用户列表
1. 查询用户
需要用户分页列表接口。
可以根据用户名模糊搜索。
可以进行手机号的搜索。
可以进行状态的查询。
1.1 接口分析
请求方式 | 请求路径 | 是否需求token头 |
---|---|---|
GET | system/user/list | 是 |
请求参数query格式:
pageNum: 页码
pageSize: 每页条数
userName:用户名
phonenumber:手机号
status:状态
响应格式:
{
"code":200,
"data":{
"rows":[
{
"avatar":"http://r7yxkqloa.bkt.clouddn.com/2022/03/05/75fd15587811443a9a9a771f24da458d.png",
"createTime":"2022-01-05 17:01:56",
"email":"23412332@qq.com",
"id":"1",
"nickName":"sg3334",
"phonenumber":"18888888888",
"sex":"1",
"status":"0",
"updateBy":"1",
"updateTime":"2022-03-13 21:36:22",
"userName":"sg"
}
],
"total":"1"
},
"msg":"操作成功"
}
1.2 代码实现
第一步:keke-admin的controller层新建UserController
package com.keke.controller;
import com.keke.domain.ResponseResult;
import com.keke.domain.entity.User;
import com.keke.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/system/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public ResponseResult selectPageUser(User user, Integer pageNum, Integer pageSize){
return userService.selectPageUser(user,pageNum,pageSize);
}
}
第二步:service层
package com.keke.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.RegisterUserDto;
import com.keke.domain.dto.UserInfoDto;
import com.keke.domain.entity.User;
import org.springframework.stereotype.Service;
/**
* 用户表(User)表服务接口
*
* @author makejava
* @since 2023-10-13 09:08:38
*/
public interface UserService extends IService<User> {
ResponseResult userInfo();
ResponseResult updateUserInfo(UserInfoDto userInfoDto);
ResponseResult register(RegisterUserDto registerUserDto);
//后台接口分页查询用户
ResponseResult selectPageUser(User user, Integer pageNum, Integer pageSize);
}
第三步:impl层
package com.keke.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.RegisterUserDto;
import com.keke.domain.dto.UserInfoDto;
import com.keke.domain.entity.User;
import com.keke.domain.vo.PageVo;
import com.keke.domain.vo.UserInfoVo;
import com.keke.enums.AppHttpCodeEnum;
import com.keke.handler.exception.exception.SystemException;
import com.keke.mapper.UserMapper;
import com.keke.service.UserService;
import com.keke.utils.BeanCopyUtils;
import com.keke.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
/**
* 用户表(User)表服务实现类
*
* @author makejava
* @since 2023-10-13 10:12:51
*/
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public ResponseResult userInfo() {
Long userId = SecurityUtils.getUserId();
User user = getById(userId);
UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
return ResponseResult.okResult(userInfoVo);
}
@Override
public ResponseResult updateUserInfo(UserInfoDto userInfoDto) {
User user = BeanCopyUtils.copyBean(userInfoDto, User.class);
updateById(user);
return ResponseResult.okResult();
}
@Override
public ResponseResult register(RegisterUserDto registerUserDto) {
//对前端传过来的用户名进行非空判断,例如null、"",就抛出异常
if(!StringUtils.hasText(registerUserDto.getUserName())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
}
//密码
if(!StringUtils.hasText(registerUserDto.getPassword())){
throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
}
//邮箱
if(!StringUtils.hasText(registerUserDto.getEmail())){
throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
}
//昵称
if(!StringUtils.hasText(registerUserDto.getNickName())){
throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
}
//判断用户传给我们的用户名是否在数据库已经存在。userNameExist方法是下面定义的
if(userNameExist(registerUserDto.getUserName())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
}
//判断用户传给我们的昵称是否在数据库已经存在。NickNameExist方法是下面定义的
if(nickNameExist(registerUserDto.getNickName())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
}
//判断用户传给我们的邮箱是否在数据库已经存在。NickNameExist方法是下面定义的
if(emailExist(registerUserDto.getEmail())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
}
//经过上面的判断,可以确保用户传给我们的用户名和昵称是数据库不存在的,且相关字段都不为空。就可以存入数据库
//注意用户传给我们的密码是明文,对于密码我们要转成密文之后再存入数据库。注意加密要和解密用同一套算法
//keke-blog工程的securityConfig类里面有解密算法,当时我们写了一个passwordEncoder方法,并且注入到了spring容器
//解密
String encodePassword = passwordEncoder.encode(registerUserDto.getPassword());
//封装成user存数据库中
User user = BeanCopyUtils.copyBean(registerUserDto, User.class);
//设置密码为加密的密码
user.setPassword(encodePassword);
//存入数据库中
save(user);
//封装返回
return ResponseResult.okResult();
}
@Override
public ResponseResult selectPageUser(User user, Integer pageNum, Integer pageSize) {
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//可以根据用户名模糊搜索
lambdaQueryWrapper.like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName());
//可以进行手机号的搜索
lambdaQueryWrapper.eq(StringUtils.hasText(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());
//可以根据状态进行搜索
lambdaQueryWrapper.eq(StringUtils.hasText(user.getStatus()),User::getStatus,user.getStatus());
//mp分页器
Page<User> page = new Page<>(pageNum,pageSize);
page(page,lambdaQueryWrapper);
//封装vo
PageVo pageVo = new PageVo(page.getRecords(),page.getTotal());
//响应返回
return ResponseResult.okResult(pageVo);
}
//'判断用户传给我们的用户名是否在数据库已经存在' 的方法
public boolean userNameExist(String userName){
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//查询数据库中有用户名相同的数据没有
lambdaQueryWrapper.eq(User::getUserName,userName);
//如果查出来有,就说明存在,返回true
int count = count(lambdaQueryWrapper);
return count>0;
}
//'判断用户传给我们的昵称是否在数据库已经存在' 的方法
public boolean nickNameExist(String nickName){
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//查询数据库中有用户名相同的数据没有
lambdaQueryWrapper.eq(User::getNickName,nickName);
//如果查出来有,就说明存在,返回true
int count = count(lambdaQueryWrapper);
return count>0;
}
//'判断用户传给我们的邮箱是否在数据库已经存在' 的方法
public boolean emailExist(String email){
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//查询数据库中有用户名相同的数据没有
lambdaQueryWrapper.eq(User::getEmail,email);
//如果查出来有,就说明存在,返回true
int count = count(lambdaQueryWrapper);
return count>0;
}
}
1.3 测试
2. 新增用户
需要新增用户功能。新增用户时可以直接关联角色。
注意:新增用户时注意密码加密存储。
用户名不能为空,否则提示:必需填写用户名
用户名必须之前未存在,否则提示:用户名已存在
手机号必须之前未存在,否则提示:手机号已存在
邮箱必须之前未存在,否则提示:邮箱已存在
2.1 查询角色列表接口
注意:查询的是所有状态正常的角色
2.1.1 接口分析
请求方式 | 请求路径 | 是否需求token头 |
---|---|---|
GET | /system/role/listAllRole | 是 |
响应格式:
{
"code":200,
"data":[
{
"createBy":"0",
"createTime":"2021-11-12 18:46:19",
"delFlag":"0",
"id":"1",
"remark":"超级管理员",
"roleKey":"admin",
"roleName":"超级管理员",
"roleSort":"1",
"status":"0",
"updateBy":"0"
},
{
"createBy":"0",
"createTime":"2021-11-12 18:46:19",
"delFlag":"0",
"id":"2",
"remark":"普通角色",
"roleKey":"common",
"roleName":"普通角色",
"roleSort":"2",
"status":"0",
"updateBy":"0",
"updateTime":"2022-01-02 06:32:58"
},
{
"createTime":"2022-01-06 22:07:40",
"delFlag":"0",
"id":"11",
"remark":"嘎嘎嘎",
"roleKey":"aggag",
"roleName":"嘎嘎嘎",
"roleSort":"5",
"status":"0",
"updateBy":"1",
"updateTime":"2022-09-12 10:00:25"
},
{
"createTime":"2022-01-16 14:49:30",
"delFlag":"0",
"id":"12",
"roleKey":"link",
"roleName":"友链审核员",
"roleSort":"1",
"status":"0",
"updateTime":"2022-01-16 16:05:09"
}
],
"msg":"操作成功"
}
2.1.2 代码实现
第一步:在keke-admin的controller层的RoleController新增查询状态正常角色的接口
package com.keke.controller;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.AdminAddRoleDto;
import com.keke.domain.dto.ChangeRoleStatusDto;
import com.keke.domain.dto.EditRoleDto;
import com.keke.domain.entity.Role;
import com.keke.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/system/role")
public class RoleController {
@Autowired
private RoleService roleService;
@GetMapping("/list")
public ResponseResult selectPageRole(Role role,Integer pageNum,Integer pageSize){
return roleService.selectPageRole(role,pageNum,pageSize);
}
@PutMapping("/changeStatus")
public ResponseResult changeRoleStatus(@RequestBody ChangeRoleStatusDto changeRoleStatusDto){
return roleService.changeRoleStatus(changeRoleStatusDto);
}
@PostMapping
public ResponseResult addRole(@RequestBody AdminAddRoleDto adminAddRoleDto){
return roleService.addRole(adminAddRoleDto);
}
@GetMapping("/{id}")
public ResponseResult getRoleInfo(@PathVariable("id") Long id){
return roleService.getRoleInfo(id);
}
@PutMapping
public ResponseResult editRole(@RequestBody EditRoleDto editRoleDto){
return roleService.editRole(editRoleDto);
}
@DeleteMapping("/{id}")
public ResponseResult deleteRoleById(@PathVariable("id") Long id){
roleService.removeById(id);
return ResponseResult.okResult();
}
@GetMapping("/listAllRole")
public ResponseResult listAllRole(){
return roleService.listAllRole();
}
}
第二步:service层新增
package com.keke.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.AdminAddRoleDto;
import com.keke.domain.dto.ChangeRoleStatusDto;
import com.keke.domain.dto.EditRoleDto;
import com.keke.domain.entity.Role;
import java.util.List;
/**
* 角色信息表(Role)表服务接口
*
* @author makejava
* @since 2023-10-18 21:04:06
*/
public interface RoleService extends IService<Role> {
List<String> selectRoleKeyByUserId(Long userId);
ResponseResult selectPageRole(Role role, Integer pageNum, Integer pageSize);
ResponseResult changeRoleStatus(ChangeRoleStatusDto changeRoleStatusDto);
ResponseResult addRole(AdminAddRoleDto adminAddRoleDto);
ResponseResult getRoleInfo(Long id);
ResponseResult editRole(EditRoleDto editRoleDto);
ResponseResult listAllRole();
}
第三步:impl层新增
package com.keke.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keke.constants.SystemConstants;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.AdminAddRoleDto;
import com.keke.domain.dto.ChangeRoleStatusDto;
import com.keke.domain.dto.EditRoleDto;
import com.keke.domain.entity.Role;
import com.keke.domain.entity.RoleMenu;
import com.keke.domain.vo.AdminRoleVo;
import com.keke.domain.vo.PageVo;
import com.keke.mapper.RoleMapper;
import com.keke.service.RoleMenuService;
import com.keke.service.RoleService;
import com.keke.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 角色信息表(Role)表服务实现类
*
* @author makejava
* @since 2023-10-18 21:04:06
*/
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
@Autowired
private RoleMenuService roleMenuService;
//根据用户id查询角色信息
@Override
public List<String> selectRoleKeyByUserId(Long userId) {
//如果userId为1,那么角色权限字符串就只需要返回一个admin
if(userId==1L){
List<String> roles = new ArrayList<>();
roles.add("admin");
return roles;
}
//如果用户id不为1,那么需要根据userId连表查询对应的roleId,然后再去角色表中去查询
//对应的角色权限字符串
//这里我们期望RoleMapper中封装一个方法去帮我们实现这个复杂的操作
RoleMapper roleMapper = getBaseMapper();
return roleMapper.selectRoleKeyByUserId(userId);
}
@Override
public ResponseResult selectPageRole(Role role, Integer pageNum, Integer pageSize) {
LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.like(StringUtils.hasText(role.getRoleName()),Role::getRoleName,role.getRoleName());
lambdaQueryWrapper.eq(StringUtils.hasText(role.getStatus()),Role::getStatus,role.getStatus());
lambdaQueryWrapper.orderByAsc(Role::getRoleSort);
Page<Role> page = new Page<>(pageNum,pageSize);
page(page,lambdaQueryWrapper);
PageVo pageVo = new PageVo(page.getRecords(),page.getTotal());
return ResponseResult.okResult(pageVo);
}
@Override
public ResponseResult changeRoleStatus(ChangeRoleStatusDto changeRoleStatusDto) {
Long roleId = changeRoleStatusDto.getRoleId();
Role role = getById(roleId);
role.setStatus(changeRoleStatusDto.getStatus());
updateById(role);
return ResponseResult.okResult();
}
@Transactional
@Override
public ResponseResult addRole(AdminAddRoleDto adminAddRoleDto) {
//Bean拷贝
Role role = BeanCopyUtils.copyBean(adminAddRoleDto, Role.class);
//拿到菜单权限id集合
List<Long> menuIds = adminAddRoleDto.getMenuIds();
//流式处理转化,把每一个menuId都设置到该roleId下
List<RoleMenu> roleMenuList = menuIds.stream()
.map(new Function<Long, RoleMenu>() {
@Override
public RoleMenu apply(Long menuId) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(role.getId());
roleMenu.setMenuId(menuId);
return roleMenu;
}
}).collect(Collectors.toList());
//mp批量保存到数据库中
roleMenuService.saveBatch(roleMenuList);
//封装返回
return ResponseResult.okResult();
}
@Override
public ResponseResult getRoleInfo(Long id) {
Role role = getById(id);
AdminRoleVo adminRoleVo = BeanCopyUtils.copyBean(role, AdminRoleVo.class);
return ResponseResult.okResult(adminRoleVo);
}
@Override
public ResponseResult editRole(EditRoleDto editRoleDto) {
Role role = BeanCopyUtils.copyBean(editRoleDto, Role.class);
List<Long> menuIds = editRoleDto.getMenuIds();
List<RoleMenu> roleMenuList = menuIds.stream()
.map(new Function<Long, RoleMenu>() {
@Override
public RoleMenu apply(Long menuId) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(role.getId());
roleMenu.setMenuId(menuId);
return roleMenu;
}
}).collect(Collectors.toList());
roleMenuService.saveBatch(roleMenuList);
return ResponseResult.okResult();
}
@Override
public ResponseResult listAllRole() {
LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(Role::getStatus, SystemConstants.STATUS_NORMAL);
List<Role> roleList = list(lambdaQueryWrapper);
return ResponseResult.okResult(roleList);
}
}
2.1.3 测试
2.2 新增用户接口
2.2.1 接口分析
请求方式 | 请求路径 | 是否需求token头 |
---|---|---|
POST | system/user | 是 |
请求体:
{
"userName":"wqeree",
"nickName":"测试新增用户",
"password":"1234343",
"phonenumber":"18889778907",
"email":"233@sq.com",
"sex":"0",
"status":"0",
"roleIds":[
"2"
]
}
响应格式:
{
"code":200,
"msg":"操作成功"
}
2.2.2 代码实现
第一步:keke-framework的domain/entity新增
package com.keke.domain.entity;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* 用户和角色关联表(UserRole)表实体类
*
* @author makejava
* @since 2023-10-23 21:17:14
*/
@SuppressWarnings("serial")
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_user_role")
public class UserRole {
//用户ID
private Long userId;
//角色ID
private Long roleId;
}
第二步:keke-framework的service新增
package com.keke.service;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* 用户和角色关联表(UserRole)表服务接口
*
* @author makejava
* @since 2023-10-23 21:17:32
*/
public interface UserRoleService extends IService<UserRole> {
}
第三步:keke-framework的service/impl新增
package com.keke.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keke.domain.entity.UserRole;
import com.keke.mapper.UserRoleMapper;
import com.keke.service.UserRoleService;
import org.springframework.stereotype.Service;
/**
* 用户和角色关联表(UserRole)表服务实现类
*
* @author makejava
* @since 2023-10-23 21:17:32
*/
@Service("userRoleService")
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
}
第四步:keke-framework的mapper新增
package com.keke.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.keke.domain.entity.User;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户表(User)表数据库访问层
*
* @author makejava
* @since 2023-10-11 20:26:26
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
第五步:keke-framework的domain/dto新增
package com.keke.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AdminAddUserDto {
//用户名
private String userName;
//昵称
private String nickName;
//密码
private String password;
//账号状态(0正常 1停用)
private String status;
//邮箱
private String email;
//手机号
private String phonenumber;
//用户性别(0男,1女,2未知)
private String sex;
//roleId
List<Long> roleIds;
}
第六步:keke-admin的controller层UserController新增
package com.keke.controller;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.AdminAddUserDto;
import com.keke.domain.entity.User;
import com.keke.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/system/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public ResponseResult selectPageUser(User user, Integer pageNum, Integer pageSize){
return userService.selectPageUser(user,pageNum,pageSize);
}
@PostMapping
public ResponseResult addUser(@RequestBody AdminAddUserDto adminAddUserDto){
return userService.addUser(adminAddUserDto);
}
}
第七步:service层UserService新增
package com.keke.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.AdminAddUserDto;
import com.keke.domain.dto.RegisterUserDto;
import com.keke.domain.dto.UserInfoDto;
import com.keke.domain.entity.User;
import org.springframework.stereotype.Service;
/**
* 用户表(User)表服务接口
*
* @author makejava
* @since 2023-10-13 09:08:38
*/
public interface UserService extends IService<User> {
ResponseResult userInfo();
ResponseResult updateUserInfo(UserInfoDto userInfoDto);
ResponseResult register(RegisterUserDto registerUserDto);
//后台接口分页查询用户
ResponseResult selectPageUser(User user, Integer pageNum, Integer pageSize);
ResponseResult addUser(AdminAddUserDto adminAddUserDto);
}
第八步:impl层实现方法
package com.keke.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keke.domain.ResponseResult;
import com.keke.domain.dto.AdminAddUserDto;
import com.keke.domain.dto.RegisterUserDto;
import com.keke.domain.dto.UserInfoDto;
import com.keke.domain.entity.User;
import com.keke.domain.entity.UserRole;
import com.keke.domain.vo.PageVo;
import com.keke.domain.vo.UserInfoVo;
import com.keke.enums.AppHttpCodeEnum;
import com.keke.handler.exception.exception.SystemException;
import com.keke.mapper.UserMapper;
import com.keke.service.UserRoleService;
import com.keke.service.UserService;
import com.keke.utils.BeanCopyUtils;
import com.keke.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 用户表(User)表服务实现类
*
* @author makejava
* @since 2023-10-13 10:12:51
*/
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserRoleService userRoleService;
@Override
public ResponseResult userInfo() {
Long userId = SecurityUtils.getUserId();
User user = getById(userId);
UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
return ResponseResult.okResult(userInfoVo);
}
@Override
public ResponseResult updateUserInfo(UserInfoDto userInfoDto) {
User user = BeanCopyUtils.copyBean(userInfoDto, User.class);
updateById(user);
return ResponseResult.okResult();
}
@Override
public ResponseResult register(RegisterUserDto registerUserDto) {
//对前端传过来的用户名进行非空判断,例如null、"",就抛出异常
if(!StringUtils.hasText(registerUserDto.getUserName())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
}
//密码
if(!StringUtils.hasText(registerUserDto.getPassword())){
throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
}
//邮箱
if(!StringUtils.hasText(registerUserDto.getEmail())){
throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
}
//昵称
if(!StringUtils.hasText(registerUserDto.getNickName())){
throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
}
//判断用户传给我们的用户名是否在数据库已经存在。userNameExist方法是下面定义的
if(userNameExist(registerUserDto.getUserName())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
}
//判断用户传给我们的昵称是否在数据库已经存在。NickNameExist方法是下面定义的
if(nickNameExist(registerUserDto.getNickName())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
}
//判断用户传给我们的邮箱是否在数据库已经存在。NickNameExist方法是下面定义的
if(emailExist(registerUserDto.getEmail())){
//SystemException是我们写的异常类、AppHttpCodeEnum是我们写的枚举类
throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
}
//经过上面的判断,可以确保用户传给我们的用户名和昵称是数据库不存在的,且相关字段都不为空。就可以存入数据库
//注意用户传给我们的密码是明文,对于密码我们要转成密文之后再存入数据库。注意加密要和解密用同一套算法
//keke-blog工程的securityConfig类里面有解密算法,当时我们写了一个passwordEncoder方法,并且注入到了spring容器
//解密
String encodePassword = passwordEncoder.encode(registerUserDto.getPassword());
//封装成user存数据库中
User user = BeanCopyUtils.copyBean(registerUserDto, User.class);
//设置密码为加密的密码
user.setPassword(encodePassword);
//存入数据库中
save(user);
//封装返回
return ResponseResult.okResult();
}
@Override
public ResponseResult selectPageUser(User user, Integer pageNum, Integer pageSize) {
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//可以根据用户名模糊搜索
lambdaQueryWrapper.like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName());
//可以进行手机号的搜索
lambdaQueryWrapper.eq(StringUtils.hasText(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());
//可以根据状态进行搜索
lambdaQueryWrapper.eq(StringUtils.hasText(user.getStatus()),User::getStatus,user.getStatus());
//mp分页器
Page<User> page = new Page<>(pageNum,pageSize);
page(page,lambdaQueryWrapper);
//封装vo
PageVo pageVo = new PageVo(page.getRecords(),page.getTotal());
//响应返回
return ResponseResult.okResult(pageVo);
}
@Override
public ResponseResult addUser(AdminAddUserDto adminAddUserDto) {
User user = BeanCopyUtils.copyBean(adminAddUserDto, User.class);
List<Long> roleIds = adminAddUserDto.getRoleIds();
List<UserRole> userRoleList = roleIds.stream()
.map(new Function<Long, UserRole>() {
@Override
public UserRole apply(Long roleId) {
UserRole userRole = new UserRole();
userRole.setUserId(user.getId());
userRole.setRoleId(roleId);
return userRole;
}
}).collect(Collectors.toList());
userRoleService.saveBatch(userRoleList);
return ResponseResult.okResult();
}
//'判断用户传给我们的用户名是否在数据库已经存在' 的方法
public boolean userNameExist(String userName){
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//查询数据库中有用户名相同的数据没有
lambdaQueryWrapper.eq(User::getUserName,userName);
//如果查出来有,就说明存在,返回true
int count = count(lambdaQueryWrapper);
return count>0;
}
//'判断用户传给我们的昵称是否在数据库已经存在' 的方法
public boolean nickNameExist(String nickName){
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//查询数据库中有用户名相同的数据没有
lambdaQueryWrapper.eq(User::getNickName,nickName);
//如果查出来有,就说明存在,返回true
int count = count(lambdaQueryWrapper);
return count>0;
}
//'判断用户传给我们的邮箱是否在数据库已经存在' 的方法
public boolean emailExist(String email){
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//查询数据库中有用户名相同的数据没有
lambdaQueryWrapper.eq(User::getEmail,email);
//如果查出来有,就说明存在,返回true
int count = count(lambdaQueryWrapper);
return count>0;
}
}
2.2.3 测试