博客后台
AOP实现日志记录 需求 通过日志记录接口调用信息,便于后期排查
格式如下 :
实现
先定义注解类
1 2 3 4 5 6 7 8 9 10 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface SystemLog { String businessName () ; }
定义切面类
1 2 3 4 5 6 7 8 9 @Component @Aspect @Slf4j public class LogAspect {}
定义切点,及其通知方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 @Component @Aspect @Slf4j public class LogAspect { @Pointcut("@annotation(com.blog.annotation.SystemLog)") public void pt () { } @Around("pt()") public Object printLog (ProceedingJoinPoint joinPoint) throws Throwable { joinPoint.getArgs(); Object res; try { handleBefore(joinPoint); res = joinPoint.proceed(); handleAfter(res); } finally { log.info("============End============" + System.lineSeparator()); } return res; } private void handleBefore (ProceedingJoinPoint joinPoint) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); SystemLog systemLog = getSystemLog(joinPoint); log.info("============Start============" ); log.info("URL : {}" ,request.getRequestURL()); log.info("BusinessName : {}" ,systemLog.businessName()); log.info("HTTP Method : {}" ,request.getMethod()); log.info("Class Method : {}.{}" ,joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature) joinPoint.getSignature()).getName()); log.info("IP : {}" ,request.getRemoteHost()); log.info("Request Args : {}" , JSON.toJSONString(joinPoint.getArgs()) ); } private void handleAfter (Object res) { log.info("Response : {}" , JSON.toJSONString(res)); } private SystemLog getSystemLog (ProceedingJoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class); return systemLog; } }
在需要增强的方法上添加自定义注解
1 2 3 4 5 @SystemLog(businessName="更新用户信息") @GetMapping("/userInfo") public ResponseResult userInfo () { return userService.userInfo(); }
Swagger2 依赖
1 2 3 4 5 6 7 8 <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-swagger2</artifactId > </dependency > <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-swagger-ui</artifactId > </dependency >
基本使用 1 2 3 4 5 @ApiOperation(value = "友链评论列表",notes = "获取一页友链评论") @GetMapping("/linkCommentList") public ResponseResult listCommentList (Integer pageNum , Integer pageSize) { return commentService.commentList(SystemConstants.COMMENT_TYPE_FRIEND,null ,pageNum,pageSize); }
使用@ApiOperation(value = "友链评论列表",notes = "获取一页友链评论")
来进行标注
配置形参
1 2 3 4 @ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "页号"), @ApiImplicitParam(name = "pageSize", value = "每页大小") })
**实体类接口 : **
一般一个实体类不止在一个接口中被用到,所以如果直接在实体类中添加的话就是使代码耦合,所以我们需要进行拆解
1 2 3 4 @ApiModel(description = "文章实体类") public class Article { }
所以上面的写法是不正规的
所以我们需要使用DTO对象
【dto对象 :数据传输对象 】 按照开发规范,所有的controller层需要的实体类参数,我们都需要将其转换为dto对象
1 2 3 4 5 6 @PostMapping public ResponseResult addComment (@RequestBody AddCommentDto addCommentDto) { Comment comment = BeanCopyUtils.copyBean(addCommentDto, Comment.class); return commentService.addComment(comment); }
1 2 3 4 5 6 7 8 9 10 11 12 @ApiModel(description = "添加评论实体类") public class AddCommentDto { private Long id; private String type; @ApiModelProperty(notes = "文章id") private Long articleId; }
所有的dto都是需要添加的
获取所有标签 接口
实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @RestController @RequestMapping("/content/tag") public class TagController { @Resource private TagService tagService; @GetMapping("/list") public ResponseResult list () { return ResponseResult.okResult(tagService.list()); } }
后台登录、登出 接口
登录
①自定义登录接口
调用ProviderManager的方法进行认证 如果认证成功生成jwt
把信息存入redis中
②自定义UserDetailsServic e
在这个实现类中进行查询数据库操作
注意配置密码加密BCryptPasswordCoder
校验
①自定义jwt认证过滤器
获取token
解析token获取其中的userId
从redis中获取用户信息
存入securityContextHolder
实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @RestController @RequestMapping("/user") public class loginController { @Resource private AdminLoginService loginService; @PostMapping("/login") public ResponseResult login (@RequestBody User user) { if (!StringUtils.hasText(user.getUserName())){ throw new SystemException (AppHttpCodeEnum.REQUIRE_USERNAME); } return loginService.login(user); } @PostMapping("/logout") public ResponseResult logout () { return loginService.logout(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 @Service public class AdminLoginServiceImpl implements AdminLoginService { @Autowired private AuthenticationManager authenticationManager; @Resource private RedisCache redisCache; @Override public ResponseResult login (User user) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken (user.getUserName(),user.getPassword()); Authentication authenticate = authenticationManager.authenticate(authenticationToken); if (Objects.isNull(authenticate)){ throw new RuntimeException ("用户名或密码错误" ); } LoginUser loginUser = (LoginUser) authenticate.getPrincipal(); String userId = loginUser.getUser().getId().toString(); String jwt = JwtUtil.createJWT(userId); redisCache.setCacheObject(SystemConstants.LOGIN_KEY + userId,loginUser); Map<String,String> map = new HashMap <>(); map.put("token" ,jwt); return ResponseResult.okResult(map); } @Override public ResponseResult logout () { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); Long userId = loginUser.getUser().getId(); redisCache.deleteObject(SystemConstants.LOGIN_KEY + userId); return ResponseResult.okResult(); } }
后台权限控制及其动态路由 表分析 权限表
对应的页面
权限表
角色权限表
获取当前用户的权限和角色信息 接口(getInfo)
实现getInfo 最终实现结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 { "code" : 200 , "data" : { "permissions" : [ "system:menu:list" , "system:menu:query" , "system:menu:add" , "system:menu:edit" , "system:menu:remove" , "content:article:writer" ] , "roles" : [ "common" , "link" ] , "user" : { "avatar" : "http://rrpanx30j.hd-bkt.clouddn.com/images/91529822720e0cf3efed815e0446f21fbe09aa79.png" , "email" : "23412532@qq.com" , "id" : 4 , "nickName" : "红红火火恍恍惚惚" , "sex" : "1" } } , "msg" : "操作成功" }
controller 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @RestController public class UserController { @Resource private RoleService roleService; @Resource private MenuService menuService; @GetMapping("/getInfo") public ResponseResult<AdminUserInfoVo> getInfo () { LoginUser loginUser = SecurityUtils.getLoginUser(); List<String> perms = menuService.selectPermsByUserId(loginUser.getUser().getId()); List<String> roleKeyList = roleService.selectRoleKeyByUserId(loginUser.getUser().getId()); User user = loginUser.getUser(); UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class); AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo (perms,roleKeyList,userInfoVo); return ResponseResult.okResult(adminUserInfoVo); } }
service层两个实现类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @Service public class MenuServiceImpl extends ServiceImpl <MenuMapper, Menu> implements MenuService { @Override public List<String> selectPermsByUserId (Long id) { if (id == 1 ){ LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper <>(); wrapper.in(Menu::getMenuType, SystemConstants.MENU_TYPE_C,SystemConstants.MENU_TYPE_F); wrapper.eq(Menu::getStatus,SystemConstants.LINK_STATUS_NORMAL); List<Menu> menus = list(wrapper); List<String> Perms = menus.stream().map(Menu::getPerms).collect(Collectors.toList()); return Perms; } return getBaseMapper().selectPermsByUserId(id); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Service public class RoleServiceImpl extends ServiceImpl <RoleMapper, Role> implements RoleService { @Override public List<String> selectRoleKeyByUserId (Long id) { if (id == 1 ){ List<String> roleKeys = new ArrayList <>(); roleKeys.add("admin" ); return roleKeys; } return getBaseMapper().selectRoleKeyByUserId(id); } }
对应多表联查的xml文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?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.blog.mapper.RoleMapper" > <select id ="selectRoleKeyByUserId" resultType ="java.lang.String" > SELECT r.`role_key` FROM `sys_user_role` ur LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id` WHERE ur.`user_id` = #{userId} AND r.`status` = 0 AND r.`del_flag` = 0 </select > <select id ="selectRoleIdByUserId" resultType ="java.lang.Long" > select r.id from sys_role r left join sys_user_role ur on ur.role_id = r.id where ur.user_id = #{userId} </select > </mapper >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 <?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.blog.mapper.MenuMapper" > <select id ="selectPermsByUserId" resultType ="java.lang.String" > SELECT DISTINCT m.perms FROM `sys_user_role` ur LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id` LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id` WHERE ur.`user_id` = #{userId} AND m.`menu_type` IN ('C','F') AND m.`status` = 0 AND m.`del_flag` = 0 </select > <select id ="selectAllRouterMenu" resultType ="com.blog.domain.entity.Menu" > SELECT DISTINCT m.id, m.parent_id, m.menu_name, m.path, m.component, m.visible, m.status, IFNULL(m.perms,'') AS perms, m.is_frame, m.menu_type, m.icon, m.order_num, m.create_time FROM `sys_menu` m WHERE m.`menu_type` IN ('C','M') AND m.`status` = 0 AND m.`del_flag` = 0 ORDER BY m.parent_id,m.order_num </select > <select id ="selectRouterMenuTreeByUserId" resultType ="com.blog.domain.entity.Menu" > SELECT DISTINCT m.id, m.parent_id, m.menu_name, m.path, m.component, m.visible, m.status, IFNULL(m.perms,'') AS perms, m.is_frame, m.menu_type, m.icon, m.order_num, m.create_time FROM `sys_user_role` ur LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id` LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id` WHERE ur.`user_id` = #{userId} AND m.`menu_type` IN ('C','M') AND m.`status` = 0 AND m.`del_flag` = 0 ORDER BY m.parent_id,m.order_num </select > <select id ="selectMenuListByRoleId" resultType ="java.lang.Long" > select m.id from sys_menu m left join sys_role_menu rm on m.id = rm.menu_id where rm.role_id = #{roleId} order by m.parent_id, m.order_num </select > </mapper >
动态路由接口(getRouters)
响应格式 前端为了实现动态路由的效果,需要后端有接口能够返回所有的菜单数据
注意 :返回的菜单需要体现父子菜单的层级关系
如果用户id为1 代表管理员 ,menus中需要有所有菜单类型为c或者M的,状态为,未被删除的权限
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 { "code" : 200 , "data" : { "menus" : [ { "children" : [ ] , "component" : "content/article/write/index" , "createTime" : "2022-01-08 03:39:58" , "icon" : "build" , "id" : 2023 , "isFrame" : 1 , "menuName" : "写博文" , "menuType" : "C" , "orderNum" : 0 , "parentId" : 0 , "path" : "write" , "perms" : "content:article:writer" , "status" : "0" , "visible" : "0" } , { "children" : [ { "children" : [ ] , "component" : "system/menu/index" , "createTime" : "2021-11-12 10:46:19" , "icon" : "tree-table" , "id" : 102 , "isFrame" : 1 , "menuName" : "菜单管理" , "menuType" : "C" , "orderNum" : 3 , "parentId" : 1 , "path" : "menu" , "perms" : "system:menu:list" , "status" : "0" , "visible" : "0" } ] , "createTime" : "2021-11-12 10:46:19" , "icon" : "system" , "id" : 1 , "isFrame" : 1 , "menuName" : "系统管理" , "menuType" : "M" , "orderNum" : 1 , "parentId" : 0 , "path" : "system" , "perms" : "" , "status" : "0" , "visible" : "0" } ] } , "msg" : "操作成功" }
实现getRouters controller 1 2 3 4 5 6 7 8 9 @GetMapping("/getRouters") public ResponseResult<RoutersVo> getRouters () { Long userId = SecurityUtils.getUserId(); List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId); RoutersVo routersVo = new RoutersVo (menus); return ResponseResult.okResult(routersVo); }
service层实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 @Service public class MenuServiceImpl extends ServiceImpl <MenuMapper, Menu> implements MenuService { @Override public List<Menu> selectRouterMenuTreeByUserId (Long userId) { MenuMapper menuMapper = getBaseMapper(); List<Menu> menus = null ; if (SecurityUtils.isAdmin()){ menus = menuMapper.selectAllRouterMenu(); } else { menus = menuMapper.selectRouterMenuTreeByUserId(userId); } List<Menu> menuTree = buildMenuTree(menus,0L ); return menuTree; } private List<Menu> buildMenuTree (List<Menu> menus, Long parentId) { List<Menu> menuList = menus.stream() .filter(menu -> menu.getParentId().equals(parentId)) .map(menu -> menu.setChildren(getChildren(menu, menus))) .collect(Collectors.toList()); return menuList; } private List<Menu> getChildren (Menu menu, List<Menu> menus) { List<Menu> children = menus.stream() .filter(menu1 -> menu1.getParentId().equals(menu.getId())) .map(menu1 -> menu1.setChildren(getChildren(menu1,menus))) .collect(Collectors.toList()); return children; } }
后台项目改进点 关于项目中实现后台模块中的各个菜单及其子菜单的实现
首先查询对应用户的菜单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @Override public List<Menu> selectRouterMenuTreeByUserId (Long userId) { MenuMapper menuMapper = getBaseMapper(); List<Menu> menus = null ; if (SecurityUtils.isAdmin()){ menus = menuMapper.selectAllRouterMenu(); } else { menus = menuMapper.selectRouterMenuTreeByUserId(userId); } List<Menu> menuTree = buildMenuTree(menus,0L ); return menuTree; }
接着对于那些第一级菜单进行查询(parentId == 1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 private List<Menu> buildMenuTree (List<Menu> menus, Long parentId) { List<Menu> test = new ArrayList <>(); for (Menu menu : menus){ if (menu.getParentId().equals(parentId)){ Menu menu1 = menu.setChildren(getChildren(menu, menus)); test.add(menu1); } } return test; }
查询对应的子菜单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 private List<Menu> getChildren (Menu menu, List<Menu> menus) { List<Menu> test1 = new ArrayList <>(); for (Menu menu1 : menus){ if (menu1.getParentId().equals(menu.getId())){ test1.add(menu1); } } return test1; }
改进 在上述我们的代码中,如果仅仅是实现两层菜单还可以满足, 但是如果出现菜单层级是3 、4、5…等情况我上述实现的代码就无法满足。
这是我们就需要使用到递归算法 但是这里如果单单使用递归好像很难实现
所以我们在这里可以使用函数式编程,然后在其中套用递归来实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 private List<Menu> buildMenuTree (List<Menu> menus, Long parentId) { List<Menu> menuList = menus.stream() .filter(menu -> menu.getParentId().equals(parentId)) .map(menu -> menu.setChildren(getChildren(menu, menus))) .collect(Collectors.toList()); return menuList; }
1 2 3 4 5 6 7 8 9 10 11 12 13 private List<Menu> getChildren (Menu menu, List<Menu> menus) { List<Menu> children = menus.stream() .filter(menu1 -> menu1.getParentId().equals(menu.getId())) .map(menu1 -> menu1.setChildren(getChildren(menu1,menus))) .collect(Collectors.toList()); return children; }
通过这样的该进,我们就可以实现多层菜单的查询
查询标签列表 接口
需求 :
提供标签功能,一个文章可以有多个标签。
在后台需要分页查询标签功能,要求能够根据签名进行分页查询。后期可以增加备注查询等需求
注意 :不要把删除了的标签查询出来
实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 @RestController @RequestMapping("/content/tag") public class TagController { @Resource private TagService tagService; @GetMapping("/list") public ResponseResult<PageVo> list (int pageNum, int pageSize, TagListDto tagListDto) { return tagService.pageTagList(pageNum,pageSize,tagListDto); } }
service层实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @Service("tagService") public class TagServiceImpl extends ServiceImpl <TagMapper, Tag> implements TagService { @Override public ResponseResult<PageVo> pageTagList (Integer pageNum, Integer pageSize, TagListDto tagListDto) { Page<Tag> page = new Page <>(); page.setCurrent(pageNum); page.setSize(pageSize); LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(StringUtils.hasText(tagListDto.getName()),Tag::getName,tagListDto.getName()); wrapper.eq(StringUtils.hasText(tagListDto.getRemark()),Tag::getRemark,tagListDto.getRemark()); page(page,wrapper); PageVo pageVo = new PageVo (page.getRecords(),page.getTotal()); return ResponseResult.okResult(pageVo); } }
新增标签 接口
实现 1 2 3 4 5 @PostMapping public ResponseResult addTag (@RequestBody TagListDto tagListDto) { return tagService.addTag(tagListDto); }
serivce层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Override public ResponseResult addTag (TagListDto tagListDto) { if (ObjectUtils.isEmpty(tagListDto)){ return ResponseResult.errorResult(AppHttpCodeEnum.TAG_ERROR); } Long userId = SecurityUtils.getUserId(); Tag tag = new Tag (); tag.setName(tagListDto.getName()); tag.setRemark(tagListDto.getRemark()); tag.setCreateBy(userId); save(tag); return ResponseResult.okResult(tag); }
删除标签 接口
实现 1 2 3 4 @DeleteMapping("/{id}") public ResponseResult deleteTag (@PathVariable Long id) { return tagService.deleteTag(id); }
service层
1 2 3 4 5 6 7 8 9 10 11 12 13 @Override public ResponseResult deleteTag (Long id) { UpdateWrapper<Tag> updateWrapper = new UpdateWrapper <>(); updateWrapper.eq("id" ,id); updateWrapper.set("del_flag" ,1 ); update(updateWrapper); return ResponseResult.okResult(); }
修改标签 接口
先获取接口信息
修改接口
实现
首先获取指定id的标签
1 2 3 4 @GetMapping("/{id}") public ResponseResult getTagById (@PathVariable Long id) { return tagService.getTagById(id); }
1 2 3 4 5 6 7 @Override public ResponseResult getTagById (Long id) { Tag tag = getById(id); TagDto dto = BeanCopyUtils.copyBean(tag, TagDto.class); return ResponseResult.okResult(dto); }
修改获取的内容
1 2 3 4 @PutMapping public ResponseResult updateTag (@RequestBody TagDto tagDto) { return tagService.updateTag(tagDto); }
1 2 3 4 5 6 7 8 9 10 11 @Override public ResponseResult updateTag (TagDto tagDto) { System.out.println(tagDto.toString()); UpdateWrapper<Tag> updateWrapper = new UpdateWrapper <>(); updateWrapper.eq("id" ,tagDto.getId()); updateWrapper.set("name" ,tagDto.getName()); updateWrapper.set("remark" ,tagDto.getRemark()); update(updateWrapper); return ResponseResult.okResult(); }
写文章 接口
首先获取所有的分类信息接口
获取所有的标签请求接口
上传图片接口
写博文接口
实现
首先获取所有的分类信息接口
1 2 3 4 5 @GetMapping("/category/listAllCategory") public ResponseResult listAllCategory () { return categoryService.listAllCategory(); }
1 2 3 4 5 6 7 8 9 10 @Override public ResponseResult listAllCategory () { LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper <>(); queryWrapper.eq(Category::getStatus, SystemConstants.CATEGORY_STATUS); queryWrapper.eq(Category::getDelFlag,SystemConstants.CATEGORY_NOTDEL); List<Category> list = list(queryWrapper); List<CategoryVo> categoryVo1s = BeanCopyUtils.copyBeanList(list, CategoryVo.class); return ResponseResult.okResult(categoryVo1s); }
获取所有的标签信息
1 2 3 4 5 @GetMapping("/tag/listAllTag") public ResponseResult listAllTag () { return tagService.listAllTag(); }
1 2 3 4 5 6 7 8 9 10 @Override public ResponseResult listAllTag () { LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper <>(); queryWrapper.eq(Tag::getDelFlag, SystemConstants.TAG_NOTDEL); List<Tag> list = list(queryWrapper); List<TagVo> tagVos = BeanCopyUtils.copyBeanList(list, TagVo.class); return ResponseResult.okResult(tagVos); }
上传图片接口
1 2 3 4 5 6 7 8 9 10 @RestController public class UploadController { @Autowired private UploadService uploadService; @PostMapping("/upload") public ResponseResult uploadImg (MultipartFile img) { return uploadService.uploadImg(img); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 package com.blog.service.impl;import com.blog.domain.ResponseResult;import com.blog.enums.AppHttpCodeEnum;import com.blog.service.UploadService;import com.google.gson.Gson;import com.qiniu.common.QiniuException;import com.qiniu.http.Response;import com.qiniu.storage.Configuration;import com.qiniu.storage.Region;import com.qiniu.storage.UploadManager;import com.qiniu.storage.model.DefaultPutRet;import com.qiniu.util.Auth;import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import java.io.FileInputStream;import java.io.InputStream;@ConfigurationProperties(prefix = "oss") @Service @Data public class UploadServiceImpl implements UploadService { @Override public ResponseResult uploadImg (MultipartFile img) { String originalFilename = img.getOriginalFilename(); if (!originalFilename.endsWith(".png" ) && !originalFilename.endsWith(".jpg" )){ return ResponseResult.errorResult(AppHttpCodeEnum.FILE_TYPE_ERROR); } String url = uploadOSS(img); return ResponseResult.okResult(url); } private String accessKey; private String secretKey; private String bucket; private String uploadOSS (MultipartFile imgFile) { Configuration cfg = new Configuration (Region.autoRegion()); UploadManager uploadManager = new UploadManager (cfg); String originalFilename = imgFile.getOriginalFilename(); String key = "images/" +originalFilename; try { InputStream inputStream = imgFile.getInputStream(); Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(inputStream,key,upToken,null , null ); DefaultPutRet putRet = new Gson ().fromJson(response.bodyString(), DefaultPutRet.class); System.out.println(putRet.key); System.out.println(putRet.hash); } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { } } } catch (Exception ex) { } return "http://rrpanx30j.hd-bkt.clouddn.com/images/" + originalFilename; } }
写文章实现
1 2 3 4 @PostMapping("/article") public ResponseResult writeArticle (@RequestBody ArticleVo articleVo) { return articleService.writeArticle(articleVo); }
1 2 3 4 5 6 7 8 9 10 11 @Override @Transactional public ResponseResult writeArticle (ArticleVo articleVo) { Article article = BeanCopyUtils.copyBean(articleVo, Article.class); save(article); List<ArticleTag> collect = articleVo.getTags().stream().map(tagId -> new ArticleTag (article.getId(), tagId)).collect(Collectors.toList()); articleTagService.saveBatch(collect); return ResponseResult.okResult(); }
修改文章 需求 :点击修改文章时能够跳转回到写博文页面
回显该文章的全部信息
用户可以在该页面进行修改博文信息,点击更新后可以实现修改文章
接口
根据id获取博文
修改博文
实现
按文章id查询文章回显数据
1 2 3 4 5 @GetMapping("/{id}") public ResponseResult updateBefore (@PathVariable Long id) { return articleService.updateBefore(id); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Override public ResponseResult updateBefore (Long id) { AdminArticleVo articleVo = BeanCopyUtils.copyBean(getById(id), AdminArticleVo.class); List<Long> ids = articleTagService.selectByArticleId(id); articleVo.setTags(ids); System.out.println(articleVo); return ResponseResult.okResult(articleVo); }
修改更新
1 2 3 4 5 @PutMapping public ResponseResult updateNow (@RequestBody AdminArticleVo articleVo) { return articleService.updateNow(articleVo); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 @Override public ResponseResult updateNow (AdminArticleVo articleVo) { Article article = BeanCopyUtils.copyBean(articleVo, Article.class); updateById(article); articleTagService.deleteByArticleId(articleVo.getId(),articleVo.getTags()); List<ArticleTag> collect = articleVo.getTags().stream().map(tagId -> new ArticleTag (article.getId(), tagId)).collect(Collectors.toList()); articleTagService.saveBatch(collect); return ResponseResult.okResult(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 @Service public class ArticleTagServiceImpl extends ServiceImpl <ArticleTagMapper, ArticleTag> implements ArticleTagService { @Override public List<Long> selectByArticleId (Long id) { List<ArticleTag> list = list(); List<Long> ids = new ArrayList <>(); for (ArticleTag articleTag : list){ if (articleTag.getArticleId().equals(id)){ Long tagId = articleTag.getTagId(); ids.add(tagId); } } return ids; } @Override public void deleteByArticleId (Long id,List<Long> ids) { LambdaQueryWrapper<ArticleTag> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(ArticleTag::getArticleId,id); remove(wrapper); } }
删除文章 需求 ,删除文章是指逻辑删除 ,而不是真的删除
接口
实现 1 2 3 4 @DeleteMapping("/{id}") public ResponseResult deleteArticleById (@PathVariable Long id) { return articleService.deleteArticleById(id); }
1 2 3 4 5 6 7 8 9 10 11 12 13 @Override public ResponseResult deleteArticleById (Long id) { UpdateWrapper<Article> wrapper = new UpdateWrapper <>(); wrapper.eq("id" ,id); wrapper.set("del_flag" ,SystemConstants.DELETE); update(wrapper); return ResponseResult.okResult(); }
文章列表 接口
实现 1 2 3 4 @GetMapping("/article/list") public ResponseResult articleList (int pageNum, int pageSize, ArticleSummaryDto articleSummary) { return articleService.getAllArticle(pageNum,pageSize,articleSummary); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Override public ResponseResult getAllArticle (int pageNum, int pageSize, ArticleSummaryDto articleSummary) { LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper <>(); queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_PUT); Page<Article> pageN = new Page <>(pageNum,pageSize); Page<Article> page = page(pageN, queryWrapper); List<Article> articles = page.getRecords(); List<AdminArticleVo> articleVos = BeanCopyUtils.copyBeanList(articles, AdminArticleVo.class); PageVo pageVo = new PageVo (articleVos, page.getTotal()); return ResponseResult.okResult(pageVo); }
导出Excel文件 需求 : 将我们需要的文件 ,比如标签信息等导出成为一个Excel文件
接口 实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @GetMapping("/export") public void exportExcel (HttpServletResponse response) { try { WebUtils.setDownLoadHeader("分类.xlsx" ,response); List<CategoryVo> list = categoryService.listAllCategory(); List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(list, ExcelCategoryVo.class); EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出" ) .doWrite(excelCategoryVos); } catch (Exception e) { ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR); WebUtils.renderString(response, JSON.toJSONString(result)); } }
权限控制 只针对有权限的用户访问能够访问的信息
操作
在springSecurity中添加
1 2 3 @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter {
在需要访问的方法上加
封装权限到loginUser中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 package com.blog.service.impl;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.blog.domain.entity.LoginUser;import com.blog.domain.entity.User;import com.blog.mapper.MenuMapper;import com.blog.mapper.UserMapper;import com.blog.utils.SystemConstants;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.List;import java.util.Objects;@Service public class UserDetailsServiceImpl implements UserDetailsService { @Resource private MenuMapper menuMapper; @Resource private UserMapper userMapper; @Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException { LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper <>(); queryWrapper.eq(User::getUserName,username); User user = userMapper.selectOne(queryWrapper); if (Objects.isNull(user)){ throw new RuntimeException ("用户不存在!!!" ); } if (user.getType().equals(SystemConstants.ADMIN)){ List<String> perms = menuMapper.selectPermsByUserId(user.getId()); return new LoginUser (user,perms); } return new LoginUser (user,null ); } }
菜单列表 需求 :
展示菜单列表,不需要进行分页。可以正对菜单名做模糊查询,也可以根据菜单状态进行查询。菜单要按照父菜单id 和 OrderNum进行排序
接口
实现 1 2 3 4 5 @GetMapping("/list") public ResponseResult getAll (String status,String menuName) { return menuService.getAll(status,menuName); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @Override public ResponseResult getAll (String status, String menuName) { LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(Menu::getDelFlag,SystemConstants.NOT_DELETE); wrapper.like(Objects.nonNull(menuName),Menu::getMenuName,menuName); wrapper.like(Objects.nonNull(status),Menu::getStatus,status); wrapper.orderByAsc(Menu::getParentId); wrapper.orderByAsc(Menu::getOrderNum); List<Menu> list = list(wrapper); List<MenuVo> menuVos = BeanCopyUtils.copyBeanList(list, MenuVo.class); return ResponseResult.okResult(menuVos); }
新增菜单 接口 注意: 这里的接口路径应该是:system/menu
实现 1 2 3 4 5 @PostMapping public ResponseResult addMenu (@RequestBody Menu menu) { return menuService.addMenu(menu); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Override public ResponseResult addMenu (Menu menu) { if (ObjectUtils.isEmpty(menu.getIcon())){ return ResponseResult.errorResult(AppHttpCodeEnum.ICON_NOT_NULL); } if (ObjectUtils.isEmpty(menu.getMenuName())){ return ResponseResult.errorResult(AppHttpCodeEnum.MENU_NAME_NOT_NULL); } if (ObjectUtils.isEmpty(menu.getPath())){ return ResponseResult.errorResult(AppHttpCodeEnum.PATH_NOT_NULL); } save(menu); return ResponseResult.okResult(); }
修改菜单 需求:
不能将自己的上级菜单设置自己
1 系统管理 0 1 system 1 M 0 0 system 0 2021-11-12 10:46:19 0 系统管理目录 0
接口
查询对应的菜单信息
更新菜单接口
实现
查询所要修改的信息
1 2 3 4 5 @GetMapping("/{id}") public ResponseResult selectById (@PathVariable Long id) { return menuService.selectById(id); }
1 2 3 4 5 6 7 @Override public ResponseResult selectById (Long id) { Menu menu = getById(id); MenuVo menuVo = BeanCopyUtils.copyBean(menu, MenuVo.class); return ResponseResult.okResult(menuVo); }
修改,要求 不能使父菜单设置成为自己本身
1 2 3 4 @PutMapping public ResponseResult updateMenu (@RequestBody Menu menu) { return menuService.updateMenu(menu); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Override public ResponseResult updateMenu (Menu menu) { System.out.println(menu); if (menu.getParentId().equals(menu.getId())){ return ResponseResult.errorResult(AppHttpCodeEnum.PARENT_NOT_SELF); } LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(Menu::getId,menu.getId()); remove(wrapper); save(menu); return ResponseResult.okResult(); }
删除菜单 要求 : 不能删除有子菜单的,逻辑删除
1 2 3 4 @DeleteMapping("/{id}") public ResponseResult deleteById(@PathVariable Long id){ return menuService.deleteById(id); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Override public ResponseResult deleteById (Long id) { Menu menu = getById(id); List<Menu> list = list(); for (Menu children: list) { if (children.getParentId().equals(id)) { System.out.println("不能删除!" ); return ResponseResult.errorResult(AppHttpCodeEnum.CHILDREN_NOT_NULL); } } UpdateWrapper<Menu> wrapper= new UpdateWrapper <>(); wrapper.eq("id" ,id); wrapper.set("del_flag" ,SystemConstants.DELETE); update(wrapper); return ResponseResult.okResult(); }
角色列表 接口
实现
1 2 3 4 5 @GetMapping("/list") public ResponseResult getList (int pageNum, int pageSize,String roleName,String status) { return roleService.getList(pageNum,pageSize,roleName,status); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 @Override public ResponseResult getList (int pageNum, int pageSize, String roleName, String status) { LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(Role::getDelFlag, SystemConstants.NOT_DELETE); wrapper.orderByAsc(Role::getRoleSort); wrapper.like(Objects.nonNull(roleName),Role::getRoleName,roleName); wrapper.like(Objects.nonNull(status),Role::getStatus,status); Page<Role> page = new Page <>(pageNum,pageSize); page(page,wrapper); List<Role> records = page.getRecords(); List<RoleVo> roleVos = BeanCopyUtils.copyBeanList(records, RoleVo.class); PageVo pageVos = new PageVo (roleVos,page.getTotal()); return ResponseResult.okResult(pageVos); }
改变角色状态 接口
实现 1 2 3 4 5 6 7 8 9 10 11 @PutMapping("/changeStatus") public ResponseResult changeStatus (@RequestBody RoleDto roleDto) { System.out.println("----------" + roleDto); return roleService.changeStatus(roleDto); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Override public ResponseResult changeStatus (RoleDto roleDto) { UpdateWrapper<Role> wrapper = new UpdateWrapper <>(); wrapper.eq("id" ,roleDto.getRoleId()); wrapper.set("status" ,roleDto.getStatus()); update(wrapper); Role byId = getById(roleDto.getRoleId()); return ResponseResult.okResult(); }
新增角色 接口
响应格式:
实现新增接口
实现 1 2 3 4 5 6 7 8 9 10 @GetMapping("/treeselect") public ResponseResult treeselect () { List<Menu> menus = menuService.selectMenuList(new Menu ()); List<MenuTreeVo> options = SystemConverter.buildMenuSelectTree(menus); return ResponseResult.okResult(options); }
获取子菜单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class SystemConverter { private SystemConverter () { } public static List<MenuTreeVo> buildMenuSelectTree (List<Menu> menus) { List<MenuTreeVo> MenuTreeVos = menus.stream() .map(m -> new MenuTreeVo (null , m.getId(), m.getMenuName(), m.getParentId())) .collect(Collectors.toList()); List<MenuTreeVo> options = MenuTreeVos.stream() .filter(o -> o.getParentId().equals(0L )) .map(o -> o.setChildren(getChildList(MenuTreeVos, o))) .collect(Collectors.toList()); return options; } private static List<MenuTreeVo> getChildList (List<MenuTreeVo> list, MenuTreeVo option) { List<MenuTreeVo> options = list.stream() .filter(o -> Objects.equals(o.getParentId(), option.getId())) .map(o -> o.setChildren(getChildList(list, o))) .collect(Collectors.toList()); return options; } }
添加角色
1 2 3 4 @PostMapping public ResponseResult AddRole (@RequestBody RoleDto roleDto) { return roleService.AddRole(roleDto); }
1 2 3 4 5 6 @Override public ResponseResult AddRole (RoleDto roleDto) { Role role = BeanCopyUtils.copyBean(roleDto, Role.class); save(role); return ResponseResult.okResult(); }
修改角色信息 接口
信息回显
加载角色菜单树请求
进行修改
实现
实现信息回显
1 2 3 4 5 6 7 8 9 10 11 @Override public ResponseResult getRoleById (Long id) { Role role = getById(id); RoleVo roleVo = BeanCopyUtils.copyBean(role, RoleVo.class); return ResponseResult.okResult(roleVo); }
实现权限树的回显
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @GetMapping("/roleMenuTreeselect/{id}") public ResponseResult roleMenuTreeSelect (@PathVariable Long id) { List<Menu> menus = menuService.selectMenuList(new Menu ()); LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(RoleMenu::getRoleId,id); List<RoleMenu> list = roleMenuService.list(wrapper); List<Long> ids = new ArrayList <>(); for (RoleMenu menu : list){ Long menuId = menu.getMenuId(); ids.add(menuId); } List<MenuTreeVo> menuTreeVos = SystemConverter.buildMenuSelectTree(menus); RoleMenuTreeSelectVo vo = new RoleMenuTreeSelectVo (ids, menuTreeVos); return ResponseResult.okResult(vo); }
实现信息修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @Override public ResponseResult updateRole (Role role) { updateById(role); LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper = new LambdaQueryWrapper <>(); roleMenuLambdaQueryWrapper.eq(RoleMenu::getRoleId,role.getId()); roleMenuService.remove(roleMenuLambdaQueryWrapper); Long[] menuIds = role.getMenuIds(); for (Long id : menuIds){ roleMenuService.save(new RoleMenu (role.getId(),id)); } return ResponseResult.okResult(); }
删除角色 接口&实现 1 2 3 4 @DeleteMapping("/{id}") public ResponseResult deleteRole (@PathVariable Long id) { return roleService.deleteRole(id); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Override public ResponseResult deleteRole (Long id) { UpdateWrapper<Role> wrapper = new UpdateWrapper <>(); wrapper.eq("id" ,id); wrapper.set("del_flag" ,SystemConstants.DELETE); update(wrapper); LambdaQueryWrapper<RoleMenu> roleMenuLambdaQueryWrapper = new LambdaQueryWrapper <>(); roleMenuLambdaQueryWrapper.eq(RoleMenu::getRoleId,id); roleMenuService.remove(roleMenuLambdaQueryWrapper); return ResponseResult.okResult(); }
用户列表 接口
实现 1 2 3 4 5 6 @GetMapping("/list") public ResponseResult list (int pageNum ,int pageSize,String userName,String status,String phonenumber) { return userService.listAll(pageNum,pageSize,userName,status,phonenumber); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @Override public ResponseResult listAll (int pageNum, int pageSize, String userName, String status,String phonenumber) { LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper <>(); wrapper.like(StringUtils.hasText(userName),User::getUserName,userName); wrapper.eq(StringUtils.hasText(status),User::getStatus,status); wrapper.eq(StringUtils.hasText(phonenumber),User::getPhonenumber,phonenumber); Page<User> page = new Page <>(pageNum,pageSize); page(page,wrapper); List<User> records = page.getRecords(); List<UserVo> userVos = BeanCopyUtils.copyBeanList(records, UserVo.class); PageVo pageVo = new PageVo (userVos,page.getTotal()); return ResponseResult.okResult(pageVo); }
新增用户 需求分析
首先要返回所有的角色列表(状态正常,没有删除的 )
用户输入密码存储时需要进行加密存储
相关信息不能为空
相关用户名、手机号、邮箱…不能相同
接口
查询角色列表
添加用户
实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 @Override @Transactional public ResponseResult addUser (User userDto) { if (!StringUtils.hasText(userDto.getUserName())){ ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_NOT_NULL); } if (!StringUtils.hasText(userDto.getPassword())){ ResponseResult.errorResult(AppHttpCodeEnum.PASSWORD_NOT_NULL); } if ( !StringUtils.hasText(userDto.getEmail())){ ResponseResult.errorResult(AppHttpCodeEnum.EMAIL_NOT_NULL); } if ( !StringUtils.hasText(userDto.getNickName())){ ResponseResult.errorResult(AppHttpCodeEnum.NICKNAME_EXIST); } if (usernameExist(userDto.getUserName())){ ResponseResult.errorResult(USERNAME_EXIST); } if (nickNameExist(userDto.getNickName())){ ResponseResult.errorResult(NICKNAME_EXIST); } if (phoneNumberExist(userDto.getPhonenumber())){ ResponseResult.errorResult(PHONENUMBER_EXIST); } if (EmailExist(userDto.getEmail())){ ResponseResult.errorResult(EMAIL_EXIST); } System.out.println("-------------" + userDto.getPassword()); userDto.setPassword(passwordEncoder.encode(userDto.getPassword())); save(userDto); List<Long> roleIds = userDto.getRoleIds(); for (Long roleId : roleIds){ userRoleService.save(new UserRole (userDto.getId(),roleId)); } return ResponseResult.okResult(); }
修改用户 接口
回显信息
更新
实现
获取信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 @Override public ResponseResult getUserById (Long id) { User user = getById(id); List<Role> roles = roleService.list(); LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(UserRole::getUserId,id); List<UserRole> list = userRoleService.list(wrapper); List<Long> ids = new ArrayList <>(); for (UserRole userRole : list){ ids.add(userRole.getRoleId()); } UserUpdateDataVo vo = new UserUpdateDataVo (ids, roles, user); return ResponseResult.okResult(vo); }
进行修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Override @Transactional public ResponseResult updateUser (User user) { updateById(user); LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper <>(); wrapper.eq(UserRole::getUserId,user.getId()); userRoleService.remove(wrapper); List<Long> roleIds = user.getRoleIds(); for (Long roleId : roleIds){ userRoleService.save(new UserRole (user.getId(),roleId)); } return ResponseResult.okResult(); }
删除用户 接口&实现
1 2 3 4 5 6 7 8 9 10 11 12 13 @Override public ResponseResult deleteUser (Long id) { UpdateWrapper<User> wrapper = new UpdateWrapper <>(); wrapper.eq("id" ,id); wrapper.set("del_flag" , SystemConstants.DELETE); update(wrapper); return ResponseResult.okResult(); }
分类查询 接口
实现 1 2 3 4 5 6 @GetMapping("list") public ResponseResult listAll (int pageNum ,int pageSize,CategoryVo categoryVo) { return categoryService.listAllPage(pageNum,pageSize,categoryVo); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @Override public ResponseResult listAllPage (int pageNum, int pageSize,CategoryVo categoryVo) { LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper <>(); queryWrapper.like(Objects.nonNull(categoryVo.getName()),Category::getName,categoryVo.getName()); queryWrapper.like(Objects.nonNull(categoryVo.getStatus()),Category::getStatus,categoryVo.getStatus()); queryWrapper.eq(Category::getStatus, SystemConstants.CATEGORY_STATUS); queryWrapper.eq(Category::getDelFlag,SystemConstants.CATEGORY_NOTDEL); Page<Category> page = new Page <>(pageNum,pageSize); page(page,queryWrapper); List<Category> records = page.getRecords(); List<CategoryVo> list = BeanCopyUtils.copyBeanList(records, CategoryVo.class); PageVo pageVo = new PageVo (list,page.getTotal()); return ResponseResult.okResult(pageVo); }
新增分类 接口
实现 1 2 3 4 5 6 7 8 9 10 11 @Override public ResponseResult addCategory (CategoryVo categoryVo) { Category category = BeanCopyUtils.copyBean(categoryVo, Category.class); save(category); return ResponseResult.okResult(); }
修改分类 接口
修改
实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Override public ResponseResult getCategoryById (Long id) { Category byId = getById(id); CategoryVo categoryVo = BeanCopyUtils.copyBean(byId, CategoryVo.class); return ResponseResult.okResult(categoryVo); } @Override @Transactional public ResponseResult updateCategory (CategoryVo categoryVo) { Category category = BeanCopyUtils.copyBean(categoryVo, Category.class); updateById(category); return ResponseResult.okResult(); }
删除分类 接口& 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 @Override public ResponseResult deleteCategory (Long id) { UpdateWrapper<Category> wrapper = new UpdateWrapper <>(); wrapper.eq("id" ,id); wrapper.set("del_flag" ,SystemConstants.DELETE); update(wrapper); return ResponseResult.okResult(); }
友链列表 接口
1 2 3 4 @GetMapping("/list") public ResponseResult getAllLink (int pageNum ,int pageSize ,String name ,String status) { return linkService.getAll(pageNum,pageSize,name,status); }
1 2 3 4 5 6 7 8 9 10 @Override public ResponseResult getAll (int pageNum, int pageSize, String name, String status) { LambdaQueryWrapper<Link> wrapper = new LambdaQueryWrapper <>(); wrapper.like(StringUtils.hasText(name),Link::getName,name); wrapper.eq(StringUtils.hasText(status),Link::getStatus,status); Page<Link> page = new Page <>(pageNum,pageSize); page(page,wrapper); PageVo pageVo = new PageVo (page.getRecords(),page.getTotal()); return ResponseResult.okResult(pageVo); }
新增友链 接口
1 2 3 4 @PostMapping public ResponseResult addLink (@RequestBody Link link) { return ResponseResult.okResult(linkService.save(link)); }
修改友链 1 2 3 4 5 6 7 8 9 10 11 @GetMapping("/{id}") public ResponseResult getLinkById (@PathVariable Long id) { Link byId = linkService.getById(id); return ResponseResult.okResult(byId); } @PutMapping @Transactional public ResponseResult updateLink (@RequestBody Link link) { linkService.updateById(link); return ResponseResult.okResult(); }
删除友链 1 2 3 4 5 6 7 8 @DeleteMapping("/{id}") public ResponseResult deleteLink (@PathVariable Long id) { UpdateWrapper<Link> wrapper = new UpdateWrapper <>(); wrapper.eq("id" ,id); wrapper.set("del_flag" , SystemConstants.DELETE); linkService.update(wrapper); return ResponseResult.okResult(); }