Compare commits

...

5 Commits

  1. 6
      README.md
  2. 12
      document/src/main/java/com/haihang/App.java
  3. 31
      document/src/main/java/com/haihang/config/MvcConfig.java
  4. 32
      document/src/main/java/com/haihang/config/RedissonConfig.java
  5. 17
      document/src/main/java/com/haihang/config/WebExceptionAdvice.java
  6. 8
      document/src/main/java/com/haihang/constant/Constant.java
  7. 55
      document/src/main/java/com/haihang/controller/CaseController.java
  8. 46
      document/src/main/java/com/haihang/controller/ReportController.java
  9. 35
      document/src/main/java/com/haihang/controller/RoleController.java
  10. 60
      document/src/main/java/com/haihang/controller/UserController.java
  11. 24
      document/src/main/java/com/haihang/entity/Case.java
  12. 14
      document/src/main/java/com/haihang/entity/CasePageQueryDTO.java
  13. 21
      document/src/main/java/com/haihang/entity/PageResult.java
  14. 16
      document/src/main/java/com/haihang/entity/Role.java
  15. 16
      document/src/main/java/com/haihang/entity/User.java
  16. 9
      document/src/main/java/com/haihang/entity/UserCaseVO.java
  17. 18
      document/src/main/java/com/haihang/entity/UserDTO.java
  18. 12
      document/src/main/java/com/haihang/entity/UserInfo.java
  19. 47
      document/src/main/java/com/haihang/mapper/CaseMapper.java
  20. 24
      document/src/main/java/com/haihang/mapper/RoleMapper.java
  21. 28
      document/src/main/java/com/haihang/mapper/UserMapper.java
  22. 25
      document/src/main/java/com/haihang/mapper/UserRoleMapper.java
  23. 20
      document/src/main/java/com/haihang/service/CaseService.java
  24. 19
      document/src/main/java/com/haihang/service/ReportService.java
  25. 12
      document/src/main/java/com/haihang/service/RoleService.java
  26. 19
      document/src/main/java/com/haihang/service/UserService.java
  27. 113
      document/src/main/java/com/haihang/service/impl/CaseServiceImpl.java
  28. 52
      document/src/main/java/com/haihang/service/impl/ReportServiceImpl.java
  29. 46
      document/src/main/java/com/haihang/service/impl/RoleServiceImpl.java
  30. 138
      document/src/main/java/com/haihang/service/impl/UserServiceImpl.java
  31. 67
      document/src/main/java/com/haihang/utils/LoginInterceptor.java
  32. 30
      document/src/main/java/com/haihang/utils/Result.java
  33. 20
      document/src/main/java/com/haihang/utils/UserHolder.java
  34. 39
      document/src/main/resources/application.yaml
  35. 25
      document/src/main/resources/mapper/CaseMapper.xml
  36. 8
      document/src/main/resources/mapper/userMapper.xml
  37. 97
      pom.xml

6
README.md

@ -1,3 +1,7 @@
# excise-demo
练习
用户表没密码,统一成123456在逻辑中判断。
用户新增时要指定好它对应的角色
新建角色不需要指定他关联的用户
删除用户或角色都要先删除他们对应的关联表。
部门修改相当于部门改名字了,部门对应的用户原班人马应该不变。

12
document/src/main/java/com/haihang/App.java

@ -0,0 +1,12 @@
package com.haihang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

31
document/src/main/java/com/haihang/config/MvcConfig.java

@ -0,0 +1,31 @@
package com.haihang.config;
import com.haihang.utils.LoginInterceptor;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* mvc配置
*
* @author CHEN
* @date 2022/10/07
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//登陆拦截器
registry
.addInterceptor(new LoginInterceptor(stringRedisTemplate))
.excludePathPatterns("/user/login");
}
}

32
document/src/main/java/com/haihang/config/RedissonConfig.java

@ -0,0 +1,32 @@
package com.haihang.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* redisson配置
*
* @author CHEN
* @date 2022/10/10
*/
@Configuration
public class RedissonConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private String port;
@Bean
public RedissonClient redissonClient(){
//配置
Config config=new Config();
config.useSingleServer().setAddress("redis://"+host+":"+port);
//创建对并且返回
return Redisson.create(config);
}
}

17
document/src/main/java/com/haihang/config/WebExceptionAdvice.java

@ -0,0 +1,17 @@
package com.haihang.config;
import com.haihang.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {
@ExceptionHandler(RuntimeException.class)
public Result handleRuntimeException(RuntimeException e) {
log.error(e.toString(), e);
return Result.fail("服务器异常:"+e.getMessage());
}
}

8
document/src/main/java/com/haihang/constant/Constant.java

@ -0,0 +1,8 @@
package com.haihang.constant;
public class Constant {
public static String LOGIN_COUNT_KEY = "login:count:";//登录次数
public static String LOGIN_LOCK_KEY = "login:lock:";//1代表被锁定
public static String LOGIN_USER_KEY = "login:token:";
}

55
document/src/main/java/com/haihang/controller/CaseController.java

@ -0,0 +1,55 @@
package com.haihang.controller;
import com.haihang.entity.Case;
import com.haihang.entity.CasePageQueryDTO;
import com.haihang.entity.PageResult;
import com.haihang.service.CaseService;
import com.haihang.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/case")
public class CaseController {
//用例相关接口
@Autowired
private CaseService caseService;
@PostMapping("/add")
public Result add(@RequestBody Case _case){
return caseService.add(_case);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable int id){
//根据id删除用例,删除一个用例他的子用例会一并全部删除
return caseService.deleteWithSonById(id);
}
@PutMapping("update")
public Result update(@RequestBody Case _case){
//修改用例,只能修改用例名字和用例描述
return caseService.update(_case);
}
@GetMapping("/{id}")
public Result get(@PathVariable int id){
//根据id查询用例信息接口
return caseService.getById(id);
}
@GetMapping("/page")
public Result page(CasePageQueryDTO casePageQueryDTO){
log.info("用例分页查询:{}",casePageQueryDTO);
PageResult pageResult = caseService.pageQuery(casePageQueryDTO);
return Result.ok(pageResult);
}
}

46
document/src/main/java/com/haihang/controller/ReportController.java

@ -0,0 +1,46 @@
package com.haihang.controller;
import com.haihang.service.ReportService;
import com.haihang.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.Date;
@RequestMapping("/report")
@RestController
public class ReportController {
@Autowired
private ReportService reportService;
@GetMapping("/{id}")
public Result userCases(@PathVariable Integer id) {
//根据用户id统计用户创建的用例数量
return reportService.userCases(id);
}
@GetMapping("/dayCase")
public Result dayCase(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
return reportService.dayCase(date);
}
@GetMapping("/beforeDayUserCase")
public Result beforeDayUserCase(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date,Integer userId) {
// 3. 统计到指定日期,每个用户的用例数
return reportService.beforeDayUserCase(date,userId);
}
@GetMapping("/userAndRole")
public Result userAndRole(Integer roleId) {
return reportService.countUserByRoleId(roleId);
}
}

35
document/src/main/java/com/haihang/controller/RoleController.java

@ -0,0 +1,35 @@
package com.haihang.controller;
import com.haihang.entity.Role;
import com.haihang.service.RoleService;
import com.haihang.utils.Result;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/role")
public class RoleController {
@Autowired
private RoleService roleService;
@PutMapping("/add")
public Result add(Role role) {
return roleService.add(role);
}
@Delete("/{id}")
public Result delete(@PathVariable Integer id) {
return roleService.delete(id);
}
@PutMapping("/update")
public Result update(@RequestBody Role role) {
return roleService.update(role);
}
}

60
document/src/main/java/com/haihang/controller/UserController.java

@ -0,0 +1,60 @@
package com.haihang.controller;
import com.haihang.entity.User;
import com.haihang.entity.UserDTO;
import com.haihang.service.UserService;
import com.haihang.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
* 用户登录接口
*/
@PostMapping("/login")
public Result login(@RequestBody User user) {
//接收一个用户登录名和用户的密码,因为数据库中没有密码字段,所以可以直接把密码存数据库里面。
//因为没有注册接口,可以做一个缓存预热。提前存用户密码
return userService.login(user);
}
@PutMapping("/add")
public Result add(@RequestBody UserDTO user) {
//新增用户
log.info("新增用户:{}",user);
return userService.add(user);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable("id") int id) {
log.info("删除用户的id:{}",id);
return userService.deleteUserById(id);
}
@GetMapping("/{id}")
public Result getUserById(@PathVariable("id") int id) {
log.info("查询用户:{}",id);
return userService.selectUserById(id);
}
@PutMapping("/updat")
public Result update(@RequestBody UserDTO userDTO) {
return userService.update(userDTO);
}
}

24
document/src/main/java/com/haihang/entity/Case.java

@ -0,0 +1,24 @@
package com.haihang.entity;
import lombok.Data;
import org.apache.ibatis.annotations.Insert;
import java.util.Date;
//用例信息,与数据库完全相同
@Data
public class Case {
private int id;
private String caseName;
private int parentId;
private int isLeaf;
private int createUser;
private int updateUser;
private Date createTime;
private Date updateTime;
private String caseDesc;//用例描述
}

14
document/src/main/java/com/haihang/entity/CasePageQueryDTO.java

@ -0,0 +1,14 @@
package com.haihang.entity;
import lombok.Data;
import java.io.Serializable;
//用例分页查询DTO
@Data
public class CasePageQueryDTO implements Serializable {
private String caseName;
private int page;//当前页码
private int pageSize;//每页有多大?
}

21
document/src/main/java/com/haihang/entity/PageResult.java

@ -0,0 +1,21 @@
package com.haihang.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
//分页结果
@Data
@NoArgsConstructor
public class PageResult {
private int total;
private List records;
public PageResult(int total, List records) {
this.total = total;
this.records = records;
}
}

16
document/src/main/java/com/haihang/entity/Role.java

@ -0,0 +1,16 @@
package com.haihang.entity;
import lombok.Data;
import java.util.Date;
@Data
public class Role {
private int id;
private String roleName;
private String roleCode; //英文代号
private Date createTime;
private Date updateTime;
}

16
document/src/main/java/com/haihang/entity/User.java

@ -0,0 +1,16 @@
package com.haihang.entity;
import lombok.Data;
import java.util.Date;
@Data
public class User {
private int id;//id
private String password;
private String loginName;//登录名
private String userChnName;//用户中文名
private Date createTime;
private Date updateTime;
}

9
document/src/main/java/com/haihang/entity/UserCaseVO.java

@ -0,0 +1,9 @@
package com.haihang.entity;
import lombok.Data;
@Data
public class UserCaseVO {
//用户用例大全
}

18
document/src/main/java/com/haihang/entity/UserDTO.java

@ -0,0 +1,18 @@
package com.haihang.entity;
import lombok.Data;
import java.util.Date;
@Data
public class UserDTO {
private int id;//id
private String loginName;//登录名
private String userChnName;//用户中文名
private int roleId;//前端传过来的角色id。新增用户时要指定他的角色是什么。
}

12
document/src/main/java/com/haihang/entity/UserInfo.java

@ -0,0 +1,12 @@
package com.haihang.entity;
import lombok.Data;
//用来存放token的用户简单信息
@Data
public class UserInfo {
private int id;
private String loginName;
private String UserChnName;
}

47
document/src/main/java/com/haihang/mapper/CaseMapper.java

@ -0,0 +1,47 @@
package com.haihang.mapper;
import com.github.pagehelper.Page;
import com.haihang.entity.Case;
import com.haihang.entity.CasePageQueryDTO;
import org.apache.ibatis.annotations.*;
import java.time.LocalDate;
import java.util.List;
@Mapper
public interface CaseMapper {
@Select("select * from case_table where id = #{parentId}")
Case selectById(int parentId);
@Insert("INSERT INTO `case_table`\n" +
"(id, case_name, parent_id, is_leaf, create_user, update_user, create_time, update_time, case_desc)\n" +
"VALUES(null, #{caseName}, #{parentId}, 1, #{createUser}, #{updateUser}, #{createTime}, #{updateTime}, #{caseDesc});")
void insert(Case aCase);
@Update("update case_table set is_leaf = #{isLeaf},case_name = #{caseName},parent_id = #{parentId}" +
", update_user = #{updateUser},update_time = null ,case_desc=#{caseDesc} " +
"where id = #{id}")
void update(Case parentCase);
@Delete("delete from case_table where id = #{id}")
void deleteById(int id);
@Select("select id from case_table where parent_id =#{id}")
List<Integer> selectByParentId(int id);
@Update("update case_table set is_leaf = #{i} where id =#{parentId}")
void updateIsLeaf(int i, int parentId);
Page<Case> pageQuery(CasePageQueryDTO casePageQueryDTO);
@Select("select id from case_table where create_user =#{id}")
List<Integer> queryByUserId(int id);
@Select("select id from case_table where DATE(create_time) = #{date}")
List<Integer> queryByDate(String date);
Integer queryBeforeDateByUser(LocalDate date, int userId);
}

24
document/src/main/java/com/haihang/mapper/RoleMapper.java

@ -0,0 +1,24 @@
package com.haihang.mapper;
import com.haihang.entity.Role;
import com.haihang.entity.User;
import org.apache.ibatis.annotations.*;
@Mapper
public interface RoleMapper {
@Insert("insert into user (ID, ROLE_NAME,ROLE_CODE,CREATE_TIME,UPDATE_TIME) values " +
" (null,#{roleName},#{roleCode},now(),now())")
void insertRole(Role role);
@Delete("delete from role where id=#{id}")
void deleteRoleById(int id);
@Select("select * from role where id=#{id}")
User getRoleById(int id);
@Update("update role set ROLE_NAME = #{roleName},ROLE_CODE =#{roleCode} where ROLE_ID=#{id}")
void update(Role role);
}

28
document/src/main/java/com/haihang/mapper/UserMapper.java

@ -0,0 +1,28 @@
package com.haihang.mapper;
import com.haihang.entity.User;
import com.haihang.entity.UserDTO;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserMapper {
@Select("select * from user where LOGIN_NAME = #{loginName}")
User getUserByLoginName(String loginName);
@Insert("insert into user (ID, LOGIN_NAME,USER_CHN_NAME,CREATE_TIME,UPDATE_TIME) values " +
" (null,#{loginName},#{userChnName},now(),now())")
@Options(useGeneratedKeys = true, keyProperty = "id", flushCache = Options.FlushCachePolicy.TRUE)
void insertUser(User user);
@Delete("delete from user where id=#{id}")
void deleteUserById(int id);
@Select("select * from user where id=#{id}")
User getUserById(int id);
@Update("update user set LOGIN_NAME = #{loginName},USER_CHN_NAME =#{userChnName} where id =#{id} ")
void updateUser(UserDTO userDTO);
}

25
document/src/main/java/com/haihang/mapper/UserRoleMapper.java

@ -0,0 +1,25 @@
package com.haihang.mapper;
import com.haihang.entity.UserDTO;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserRoleMapper {
@Delete("delete from user_role_relation where USER_ID = #{userId}")
void deleteByUserId(Integer userId);
@Delete("delete from user_role_relation where ROLE_ID = #{id}")
void deleteByRoleId(int id);
@Insert("insert into user_role_relation values (null,#{roleId},#{userId})")
void insert(int userId, int roleId);
@Update("update user_role_relation " +
"set ROLE_ID = #{roleId} where USER_ID =#{id}")
void updateRoleIdByUserId(UserDTO userDTO);
@Select("select count(id) from user_role_relation where ROLE_ID =#{roleId}")
Integer CountByRoleId(Integer roleId);
}

20
document/src/main/java/com/haihang/service/CaseService.java

@ -0,0 +1,20 @@
package com.haihang.service;
import com.haihang.entity.Case;
import com.haihang.entity.CasePageQueryDTO;
import com.haihang.entity.PageResult;
import com.haihang.utils.Result;
public interface CaseService {
Result add(Case aCase);
Result deleteWithSonById(int id);
Result update(Case aCase);
Result getById(int id);
PageResult pageQuery(CasePageQueryDTO casePageQueryDTO);
}

19
document/src/main/java/com/haihang/service/ReportService.java

@ -0,0 +1,19 @@
package com.haihang.service;
import com.haihang.utils.Result;
import java.time.LocalDate;
import java.util.Date;
public interface ReportService {
Result userCases(int id);
Result dayCase(LocalDate date);
Result beforeDayUserCase(LocalDate date, int userId);
Result countUserByRoleId(Integer roleId);
}

12
document/src/main/java/com/haihang/service/RoleService.java

@ -0,0 +1,12 @@
package com.haihang.service;
import com.haihang.entity.Role;
import com.haihang.utils.Result;
public interface RoleService {
Result add(Role role);
Result delete(int id);
Result update(Role role);
}

19
document/src/main/java/com/haihang/service/UserService.java

@ -0,0 +1,19 @@
package com.haihang.service;
import com.haihang.entity.User;
import com.haihang.entity.UserDTO;
import com.haihang.utils.Result;
import org.springframework.stereotype.Service;
@Service
public interface UserService {
Result login(User user);
Result add(UserDTO user);
Result deleteUserById(int id);
Result selectUserById(int id);
Result update(UserDTO userDTO);
}

113
document/src/main/java/com/haihang/service/impl/CaseServiceImpl.java

@ -0,0 +1,113 @@
package com.haihang.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.haihang.entity.Case;
import com.haihang.entity.CasePageQueryDTO;
import com.haihang.entity.PageResult;
import com.haihang.mapper.CaseMapper;
import com.haihang.service.CaseService;
import com.haihang.utils.Result;
import com.haihang.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class CaseServiceImpl implements CaseService {
@Autowired
private CaseMapper caseMapper;
//新增用例
@Override
public Result add(Case aCase) {
aCase.setCreateTime(new Date());
aCase.setUpdateTime(new Date());
//判断传进来的用例父节点id,查询他是不是叶子节点,如果不是叶子节点则不能新增用例
int parentId = aCase.getParentId();
if(parentId == 0){
//如果父节点为空,说明还没建立树,可以直接插入
caseMapper.insert(aCase);
return Result.ok();
}
Case parentCase = caseMapper.selectById(parentId);
int isLeaf = parentCase.getIsLeaf();
if(isLeaf!=1){
return Result.fail("该用例不能添加!原因:父节点并非叶子节点");
}
aCase.setCreateUser(UserHolder.getUser().getId());
aCase.setUpdateUser(UserHolder.getUser().getId());
caseMapper.insert(aCase);
//插入完成要把父亲的isleaf修改掉.
parentCase.setIsLeaf(0);
caseMapper.update(parentCase);
return Result.ok();
}
@Override
public Result deleteWithSonById(int id) {
//先根据id查询
Case aCase = caseMapper.selectById(id);
if(aCase==null){
return Result.ok();
}
//根据当前id查询父节点为id的id列表,找他的儿子们
List<Integer> ids= caseMapper.selectByParentId(id);
//删他的儿子们
for(Integer sonId:ids){
deleteWithSonById(sonId);
}
//在删除自己之前顺便记录parentId
int parentId = aCase.getParentId();
//有值则删除自己
caseMapper.deleteById(id);
//根据他爹id判断他爹isleaf
List<Integer> brotherId= caseMapper.selectByParentId(parentId);
if(brotherId == null || brotherId.isEmpty()){
caseMapper.updateIsLeaf(1,parentId);
}
return Result.ok();
}
@Override
public Result update(Case aCase) {
Case dbCase = caseMapper.selectById(aCase.getId());
dbCase.setCaseName(aCase.getCaseName());
dbCase.setCaseDesc(aCase.getCaseDesc());
dbCase.setUpdateUser(UserHolder.getUser().getId());
dbCase.setUpdateTime(new Date());
caseMapper.update(dbCase);
return Result.ok();
}
@Override
public Result getById(int id) {
Case aCase = caseMapper.selectById(id);
return Result.ok(aCase);
}
@Override
public PageResult pageQuery(CasePageQueryDTO casePageQueryDTO) {
//开始分页查询
PageHelper.startPage(casePageQueryDTO.getPage(),casePageQueryDTO.getPageSize());
Page<Case> page = caseMapper.pageQuery(casePageQueryDTO);
long total = page.getTotal();
List<Case> list = page.getResult();
return new PageResult((int) total,list);
}
}

52
document/src/main/java/com/haihang/service/impl/ReportServiceImpl.java

@ -0,0 +1,52 @@
package com.haihang.service.impl;
import com.haihang.mapper.CaseMapper;
import com.haihang.mapper.UserRoleMapper;
import com.haihang.service.ReportService;
import com.haihang.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
@Service
public class ReportServiceImpl implements ReportService {
@Autowired
private CaseMapper caseMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Override
public Result userCases(int id) {
List<Integer> list = caseMapper.queryByUserId(id);
return Result.ok(list.size());
}
@Override
public Result dayCase(LocalDate date) {
//根据日期筛选出符合当前日期的用例
System.out.println(date.toString());
List<Integer> lis = caseMapper.queryByDate(date.toString());
return Result.ok(lis.size());
}
@Override
public Result beforeDayUserCase(LocalDate date, int userId) {
Integer lis = caseMapper.queryBeforeDateByUser(date,userId);
return Result.ok(lis);
}
@Override
public Result countUserByRoleId(Integer roleId) {
//根据角色id查询角色关联用户数
//直接查中间表就完了
Integer count = userRoleMapper.CountByRoleId(roleId);
return Result.ok(count);
}
}

46
document/src/main/java/com/haihang/service/impl/RoleServiceImpl.java

@ -0,0 +1,46 @@
package com.haihang.service.impl;
import com.haihang.entity.Role;
import com.haihang.mapper.RoleMapper;
import com.haihang.mapper.UserRoleMapper;
import com.haihang.service.RoleService;
import com.haihang.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Override
public Result add(Role role) {
roleMapper.insertRole(role);
return Result.ok();
}
@Override
public Result delete(int id) {
//删除用户记录的时候要先删除用户角色关联的信息
userRoleMapper.deleteByRoleId(id);
roleMapper.deleteRoleById(id);
return Result.ok();
}
@Override
public Result update(Role role) {
//部门改名字了,但是原本的用户没有变化
roleMapper.update(role);
return Result.ok();
}
}

138
document/src/main/java/com/haihang/service/impl/UserServiceImpl.java

@ -0,0 +1,138 @@
package com.haihang.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.haihang.constant.Constant;
import com.haihang.entity.User;
import com.haihang.entity.UserDTO;
import com.haihang.entity.UserInfo;
import com.haihang.mapper.UserMapper;
import com.haihang.mapper.UserRoleMapper;
import com.haihang.service.UserService;
import com.haihang.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.haihang.constant.Constant.LOGIN_USER_KEY;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedissonClient redissonClient;
@Autowired
private UserRoleMapper userRoleMapper;
@Override
public Result login(User user) {
//根据传过来的用户名和密码判断登录。
// 先根据用户名查询所有信息
User userDb = userMapper.getUserByLoginName(user.getLoginName());
int id = userDb.getId();
//判断是否已经被锁定
String isLock = stringRedisTemplate.opsForValue().get(Constant.LOGIN_LOCK_KEY + id);
if("1".equals(isLock)){
return Result.fail("因为错误密码次数过多!账户已经锁定!请联系管理员解锁");
}
if(!"123456".equals(user.getPassword())){
log.info("密码错误!");
//密码错误时redis中的错误记录加1
stringRedisTemplate.opsForValue().increment(Constant.LOGIN_COUNT_KEY+id);
String s = stringRedisTemplate.opsForValue().get(Constant.LOGIN_COUNT_KEY + id);
if (Integer.parseInt(s)>=5){
stringRedisTemplate.opsForValue().set(Constant.LOGIN_LOCK_KEY+id
,"1");
return Result.fail("账户将被锁定");
}
return Result.fail("用户输入密码错误");
}
//走到这里说明密码正确,清空并放行
stringRedisTemplate.delete(Constant.LOGIN_COUNT_KEY + id);
UserInfo userInfo = new UserInfo();
userInfo.setId(userDb.getId());
userInfo.setLoginName(user.getLoginName());
userInfo.setUserChnName(userDb.getUserChnName());
String token = UUID.fastUUID().toString(true);
//将用户信息存放到redis中
Map<String, Object> map = BeanUtil.beanToMap(userInfo, new HashMap<>()
, CopyOptions.create().setIgnoreNullValue(true)
.setFieldValueEditor(
(name, value) -> value.toString()
));
//保存用户信息到redis
stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, map);
//设置过期时间
stringRedisTemplate.expire(LOGIN_USER_KEY + token, 100000000000L, TimeUnit.MINUTES);
log.info("success");
return Result.ok(token);
}
@Override
public Result add(UserDTO userDTO) {
User user = new User();
// 把这个DTO解析成一个user,一个角色id然后分别存入两张表
BeanUtil.copyProperties(userDTO,user);
userMapper.insertUser(user);//插入user
int roleId = userDTO.getRoleId();
int userId = user.getId();
userRoleMapper.insert(userId,roleId);
return Result.ok();
}
@Override
public Result deleteUserById(int id) {
//删除用户时,需要优先删除用户角色关联表中用户id为id的记录
userRoleMapper.deleteByUserId(id);
userMapper.deleteUserById(id);
return Result.ok();
}
@Override
public Result selectUserById(int id) {
User user = userMapper.getUserById(id);
return Result.ok(user);
}
@Override
public Result update(UserDTO userDTO) {
//根据给定的id更新用户信息
userMapper.updateUser(userDTO);
//根据roleid更新用户对于角色
userRoleMapper.updateRoleIdByUserId(userDTO);
return Result.ok();
}
}

67
document/src/main/java/com/haihang/utils/LoginInterceptor.java

@ -0,0 +1,67 @@
package com.haihang.utils;
import cn.hutool.core.bean.BeanUtil;
import com.haihang.entity.UserInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.haihang.constant.Constant.LOGIN_USER_KEY;
/**
* 登录拦截器
*
* @author CHEN
* @date 2022/10/07
*/
public class LoginInterceptor implements HandlerInterceptor {
private final StringRedisTemplate stringRedisTemplate;
public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate=stringRedisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//解析token
//从请求头中获取token
String token = request.getHeader("authorization");
if (StringUtils.isEmpty(token)) {
//前端没传
throw new RuntimeException("前端没有携带token!");
}
//从redis中获取用户
Map<Object, Object> userMap =
stringRedisTemplate.opsForHash()
.entries(LOGIN_USER_KEY + token);
//前端的这个token没有值
if (userMap.isEmpty()) {
throw new RuntimeException("无效token!!");
}
// //hash转UserDTO存入ThreadLocal
// UserHolder.saveUser(BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false));
//走到这里说明前端传过来的token里面有值且是登录用户,放行就完事了,暂时不用ThreadLocal
//将用户id存放到ThreadLocal
UserHolder.saveUser(BeanUtil.fillBeanWithMap(userMap, new UserInfo(), false));
return true;
}
}

30
document/src/main/java/com/haihang/utils/Result.java

@ -0,0 +1,30 @@
package com.haihang.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private Boolean success;
private String errorMsg;
private Object data;
private Long total;
public static Result ok(){
return new Result(true, null, null, null);
}
public static Result ok(Object data){
return new Result(true, null, data, null);
}
public static Result ok(List<?> data, Long total){
return new Result(true, null, data, total);
}
public static Result fail(String errorMsg){
return new Result(false, errorMsg, null, null);
}
}

20
document/src/main/java/com/haihang/utils/UserHolder.java

@ -0,0 +1,20 @@
package com.haihang.utils;
import com.haihang.entity.UserDTO;
import com.haihang.entity.UserInfo;
public class UserHolder {
private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();
public static void saveUser(UserInfo user){
tl.set(user);
}
public static UserInfo getUser(){
return tl.get();
}
public static void removeUser(){
tl.remove();
}
}

39
document/src/main/resources/application.yaml

@ -0,0 +1,39 @@
server:
port: 8081
spring:
main:
allow-circular-references: true
application:
name: hmdp
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://117.72.91.159:13306/test_repo?useSSL=false&serverTimezone=UTC
username: root
password: 123456
redis:
host: 117.72.91.159
port: 16379
lettuce:
pool:
max-active: 10
max-idle: 10
min-idle: 1
time-between-eviction-runs: 10s
jackson:
default-property-inclusion: non_null # JSON处理时忽略非空字段
logging:
level:
com.haihang: debug
mybatis:
#标注待解析的mapper的xml文件位置
mapper-locations: classpath:mapper/*.xml
#标注实体类位置
type-aliases-package: com.haihang.entity
configuration:
#开启驼峰命名
map-underscore-to-camel-case: true

25
document/src/main/resources/mapper/CaseMapper.xml

@ -0,0 +1,25 @@
<?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.haihang.mapper.CaseMapper">
<select id="pageQuery" resultType="com.haihang.entity.Case">
select * from case_table
<where>
<if test="caseName!= '' and caseName != null">
and case_name like concat('%',#{caseName},'%')
</if>
</where>
</select>
<select id="queryBeforeDateByUser" resultType="java.lang.Integer">
select count(id) from case_table
<where>
<if test="date!= null">and create_time &lt; #{date}</if>
and create_user = #{userId}
</where>
</select>
</mapper>

8
document/src/main/resources/mapper/userMapper.xml

@ -0,0 +1,8 @@
<?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.haihang.mapper.UserMapper">
</mapper>

97
pom.xml

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.haihang</groupId>
<artifactId>excersice</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/><!-- lookup parent from repository -->
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.8</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.17.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.4</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Loading…
Cancel
Save