提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一.什么是五表
权限五表指基础权限控制五表,他们分别是:user(用户)表,suer_role(用户与角色中间)表,role(角色)表,以及role_permission(角色与资源中间)表,和,permission(资源)表,
当然对于公司业务的不同,可能会扩展为七表 就是组织架构表 和组织架构中间表
以下为5表截图:
这五张表直接的关系大概为:
1个用户可能会又多个角色,1个角色可能会有多个资源控制,当然也可能反过来推理,1个资源控制可能有多个角色共有,1个角色也可能共有多个用户,所以它们的关系就是多对多的关系!
二.功能实现
当用户点击登陆就会触发
并携带账户和密码到session域中或者token中
并向Spring security(安全权限框架) 发起验证
流程大概是这样的:
登陆日志的实现
代码详解以及实现:
这里在点击登陆时进行Aop日志写入:
Aop日志增强写入
package com.hz.controller;
import com.hz.domain.SysLog;
import com.hz.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
/**
* @author hz
* @date 2020/4/10 20:05
*/
@Component
@Aspect
public class LogAop {
@Autowired
private HttpServletRequest request;
@Autowired
private ISysLogService sysLogService;
private Date visitTime; // 系统访问开始时间
private Class clazz; // 访问的类
private Method method; // 访问的方法
//前置通知 主要是获取开始时间、执行的类是哪一个、执行的是哪一个方法
@Before("execution(* com.hz.controller.*.*(..))")
public void doBefore(JoinPoint joinPoint) throws NoSuchMethodException {
visitTime = new Date(); // 系统开始访问时间
clazz = joinPoint.getTarget().getClass(); // 具体要让问的类
String methodName = joinPoint.getSignature().getName(); // 获取访问的方法名称
Object[] args = joinPoint.getArgs();
// 获取具体执行的方法的 Method 对象
if (args == null || args.length == 0) {
// 获取无参数的方法
method = clazz.getMethod(methodName);
} else {
Class[] calssArgs = new Class[args.length];
for (int i = 0; i < args.length; i++) {
calssArgs[i] = args[i].getClass();
}
clazz.getMethod(methodName, calssArgs);
}
}
// 后置通知
@After("execution(* com.hz.controller.*.*(..))")
public void doAfter(JoinPoint joinPoint) throws Exception {
// 获取访问时长
long time =new Date().getTime() - visitTime.getTime();
// 获取 url
String url = "";
if (clazz != null && method != null && clazz != SysLog.class) {
// 1.获取类上的RequestMapping("/product")
RequestMapping classAnntation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
if (classAnntation != null) {
String [] calssValue = classAnntation.value();
// 2.获取方法上的RequestMapping("/findAll.do")
RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
if (methodAnnotation != null) {
String [] methodValue = methodAnnotation.value();
url = calssValue[0] + methodValue[0];
// 获取访问的IP
String ip = request.getRemoteAddr();
// 获取当前操作的用户
SecurityContext context = SecurityContextHolder.getContext(); // 从上下文中获取当前登录的用户对象
User user =(User)context.getAuthentication().getPrincipal();
String userName = user.getUsername();
// 将日志相关信息封装在SysLog 对象
SysLog sysLog = new SysLog();
sysLog.setExecutionTime(time);
sysLog.setIp(ip);
sysLog.setMethod("[类名] " + clazz.getName() + " [方法名] " + method.getName());
sysLog.setUrl(url);
sysLog.setUsername(userName);
sysLog.setVisitTime(visitTime);
System.out.println("sysLog: " + sysLog);
// 调用Service完成操作
if (clazz.getName() != "com.hz.controller.SysLogController") {
sysLogService.save(sysLog);
}
}
}
}
}
}
sysLog接口:
package com.hz.controller;
import com.github.pagehelper.PageInfo;
import com.hz.domain.SysLog;
import com.hz.service.ISysLogService;
import org.aspectj.lang.annotation.After;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* @author hz
* @date 2020/4/10 19:24
*/
@Controller
@RequestMapping("/sysLog")
public class SysLogController {
@Autowired
private ISysLogService sysLogService;
@RequestMapping("/findAll.do")
public ModelAndView findAll(@RequestParam(name = "page", defaultValue = "1") Integer pageNum, @RequestParam(name = "size")Integer pageSize) throws Exception {
ModelAndView mv = new ModelAndView();
List<SysLog> sysLogs = sysLogService.findAll(pageNum, pageSize);
PageInfo pageInfo = new PageInfo(sysLogs);
mv.addObject("pageInfo", pageInfo);
mv.setViewName("syslog-list");
return mv;
}
}
逻辑层:
package com.hz.service.impl;
import com.github.pagehelper.PageHelper;
import com.hz.dao.ISysLogDao;
import com.hz.domain.SysLog;
import com.hz.service.ISysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;
/**
* @author hz
* @date 2020/4/10 19:25
*/
@Service
@Transactional
public class SysLogServiceImpl implements ISysLogService {
@Autowired
private ISysLogDao sysLogDao;
/**
* 查询日志
* @param pageNum
* @param pageSize
* @return
* @throws Exception
*/
@Override
public List<SysLog> findAll(Integer pageNum, Integer pageSize) throws Exception{
PageHelper.startPage(pageNum, pageSize);
return sysLogDao.findAll(pageNum, pageSize);
}
/**
* 保存用户时日志写入
* @param sysLog
* @throws Exception
*/
@Override
public void save(SysLog sysLog) throws Exception {
String uuid = UUID.randomUUID().toString().replace("-", "");
sysLog.setId(uuid);
sysLogDao.save(sysLog);
}
}
dao层:
package com.hz.dao;
import com.hz.domain.SysLog;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author hz
* @date 2020/4/10 20:04
*/
public interface ISysLogDao {
@Select("select * from sysLog")
List<SysLog> findAll(Integer pageNum, Integer pageSize) throws Exception;
@Insert("insert into syslog(id,visitTime,username,ip,url,executionTime,method) values(#{id},#{visitTime},#{username},#{ip},#{url},#{executionTime},#{method})")
void save(SysLog sysLog) throws Exception;
}
用户管理模块的实现
当我们点击用户管理时会发起一次接口请求:http://localhost:8888/hz_ssm_web/user/findAll.do
我们就会拿到所有数据,然后将用户数据的id带回,就能看到用户详情
没啥特殊逻辑,dao层也就是普通的查询用户表
但是在添加用户时需要注意的时在service层需要加密
这个和MD5加密方式差不多!
为了方便理解,我查找了当时的流程图:
用户查询的业务流程图
添加用户流程图:
用户详情流程图:
查询用户所有的角色流程图:
好了废话不多说直接上代码:
用户管理 接口代码:
package com.hz.controller;
import com.hz.domain.Role;
import com.hz.domain.UserInfo;
import com.hz.service.IUserService;
import com.hz.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 14:28
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
/**
* 查询所有用户
* @return
* @throws Exception
*/
@RequestMapping("/findAll.do")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ModelAndView findAll() throws Exception {
ModelAndView mv = new ModelAndView();
List<UserInfo> userList = userService.findAll();
mv.addObject("userList", userList);
mv.setViewName("user-list");
return mv;
}
/**
* 添加用户
* @param userInfo
* @return
* @throws Exception
*/
@RequestMapping("/save.do")
@PreAuthorize("authentication.principal.username == 'admin'")
public String save(UserInfo userInfo) throws Exception {
userService.save(userInfo);
return "redirect:findAll.do";
}
@RequestMapping("/findById.do")
public ModelAndView findById(String id) throws Exception {
ModelAndView mv = new ModelAndView();
UserInfo userInfo = userService.findById(id);
mv.addObject("user", userInfo);
mv.setViewName("user-show");
return mv;
}
/**
* 查询用户以及用户可以添加的角色
* @param userId
* @return
* @throws Exception
*/
@RequestMapping("/findUserByIdAndAllRole.do")
public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id") String userId) throws Exception {
ModelAndView mv = new ModelAndView();
//1.根据用户id查询用户
UserInfo userInfo = userService.findById(userId);
//2.根据用户id查询可以添加的角色
List<Role> otherRoles = userService.findOtherRoles(userId);
mv.addObject("user", userInfo);
mv.addObject("roleList", otherRoles);
mv.setViewName("user-role-add");
return mv;
}
/**
* 给用户添加角色
* @param userId
* @param roleIds
* @return
*/
@RequestMapping("/addRoleToUser.do")
public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "ids", required = true) String[] roleIds) {
userService.addRoleToUser(userId, roleIds);
return "redirect:findAll.do";
}
}
service层代码:
package com.hz.service.impl;
import com.hz.BCryptPasswordEncoderUtils;
import com.hz.dao.IUserDao;
import com.hz.domain.Role;
import com.hz.domain.UserInfo;
import com.hz.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 14:29
*/
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
//加密使用的的
private BCryptPasswordEncoderUtils bCryptPasswordEncoder = new BCryptPasswordEncoderUtils();
/**
* 查询所有用户
* @return
* @throws Exception
*/
@Override
public List<UserInfo> findAll() throws Exception {
return userDao.findAll();
}
/**
* 添加用户
* @param userInfo
* @return
* @throws Exception
*/
@Override
public void save(UserInfo userInfo) throws Exception {
// 添加Id
Integer userId = (int) (Math.random() * Math.random() * 100000);
userInfo.setId(userId.toString());
// spring-security对密码进行加密处理
userInfo.setPassword(bCryptPasswordEncoder.encodePassword(userInfo.getPassword()));
userDao.save(userInfo);
}
/**
* 查看用户详情
* @param id
* @return
* @throws Exception
*/
@Override
public UserInfo findById(String id) throws Exception {
return userDao.finById(id);
}
/**
* 查询用户以及用户可以添加的角色
* @param userId
* @return
* @throws Exception
*/
@Override
public List<Role> findOtherRoles(String userId) {
return userDao.findOtherRoles(userId);
}
/**
* 给用户添加角色
* @param userId
* @param roleIds
* @return
*/
@Override
public void addRoleToUser(String userId, String[] roleIds) {
for(String roleId:roleIds){
userDao.addRoleToUser(userId,roleId);
}
}
/**
* 登陆使用的 更具用户名查询用户信息
* @param username
* @return
* @throws Exception
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = null;
try {
userInfo = userDao.findByUsername(username);
} catch (Exception e) {
e.printStackTrace();
}
// 处理自己的用户对象封装成UserDetails
// User user=new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles()));
User user = new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus() == 0 ? false : true, true, true, true, getAuthority(userInfo.getRoles()));
// System.out.println("user: " + user);
return user;
}
// 作用就是返回一个List集合,集合中装入的是角色描述
public List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
List<SimpleGrantedAuthority> list = new ArrayList<>();
for (Role role : roles) {
list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
// list.add(new SimpleGrantedAuthority("ROLE_USER"));
}
return list;
}
}
dao层代码:
package com.hz.dao;
import com.hz.domain.Role;
import com.hz.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 14:29
*/
public interface IUserDao {
/**
* 查询所有用户
* @return
* @throws Exception
*/
@Select("select * from users")
List<UserInfo> findAll() throws Exception;
/**
* 添加用户
* @param userInfo
* @return
* @throws Exception
*/
@Insert("insert into users(id,email,username,password,phoneNum,status) values(#{id},#{email},#{username},#{password},#{phoneNum},#{status})")
void save(UserInfo userInfo) throws Exception;
/**
* 查看用户详情 由于用户可能有多个角色 所以角色栏单独查询返回多个
* @param id
* @return
* @throws Exception
*/
@Select("select * from users where id=#{id}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "email", column = "email"),
@Result(property = "password", column = "password"),
@Result(property = "phoneNum", column = "phoneNum"),
@Result(property = "status", column = "status"),
@Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(select = "com.hz.dao.IRoleDao.findRoleByUserId"))
})
UserInfo finById(String id) throws Exception;
/**
* 查询用户以及用户可以添加的角色
* @param userId
* @return
* @throws Exception
*/
@Select("select * from role where id not in (select roleId from users_role where userId=#{userId})")
List<Role> findOtherRoles(String userId);
/**
* 给用户添加角色
* @param userId
* @param
* @return
*/
@Insert("insert into users_role(userId,roleId) values(#{userId},#{roleId})")
void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId);
/**
* 登陆使用的 更具用户名查询用户信息
* @param username
* @return
* @throws Exception
*/
@Select("select * from users where username=#{username}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "email", column = "email"),
@Result(property = "password", column = "password"),
@Result(property = "phoneNum", column = "phoneNum"),
@Result(property = "status", column = "status"),
@Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(select = "com.hz.dao.IRoleDao.findRoleByUserId"))
})
UserInfo findByUsername(String username) throws Exception;
}
这里值得注意的是由于用户可能同时拥有多个角色所以在实体类里角色该定义成 List(数组)
dao层:
public interface ISysLogDao {
@Select("select * from sysLog")
List<SysLog> findAll(Integer pageNum, Integer pageSize) throws Exception;
@Insert("insert into syslog(id,visitTime,username,ip,url,executionTime,method) values(#{id},#{visitTime},#{username},#{ip},#{url},#{executionTime},#{method})")
void save(SysLog sysLog) throws Exception;
}
角色管理模块
关于角色管理这个模块的功能,我先建议大家看看流程图,先理解业务流程,有构思概念,更加方便学习记忆
角色管理流程图
用户添加角色流程图
接口:
package com.hz.controller;
import com.hz.domain.Permission;
import com.hz.domain.Role;
import com.hz.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 3:46
*/
@Controller
@RequestMapping("/role")
public class RoleController {
@Autowired
private IRoleService roleService;
/**
* 查询所有角色
* @return
* @throws Exception
*/
@RequestMapping("/findAll.do")
public ModelAndView findAll() throws Exception {
ModelAndView mv = new ModelAndView();
List<Role> roleList = roleService.findAll();
mv.addObject("roleList", roleList);
mv.setViewName("role-list");
return mv;
}
/**
* 添加角色
* @param role
* @return
* @throws Exception
*/
@RequestMapping("/save.do")
public String save(Role role) throws Exception {
roleService.save(role);
return "redirect:findAll.do";
}
/**
* 根据角色Id删除角色
* @param roleId
* @return
* @throws Exception
*/
@RequestMapping("/deleteRole.do")
public String deleteRole(@RequestParam(name="id",required = true) String roleId) throws Exception {
roleService.deleteRoleById(roleId);
return "redirect:findAll.do";
}
/**
* 角色详情查询
* @param roleId
* @return
* @throws Exception
*/
@RequestMapping("/findById.do")
public ModelAndView findById(@RequestParam(name = "id") String roleId) throws Exception {
ModelAndView mv = new ModelAndView();
Role role = roleService.findById(roleId);
System.out.println("角色:" + role);
mv.addObject("role", role);
mv.setViewName("role-show");
return mv;
}
/**
* 给角色添加权限
* @param roleId
* @param permissionIds
* @return
* @throws Exception
*/
@RequestMapping("/addPermissionToRole.do")
public String addPermissionToRole(@RequestParam(name = "roleId", required = true) String roleId, @RequestParam(name = "ids", required = true) String[] permissionIds) throws Exception {
roleService.addPermissionToRole(roleId, permissionIds);
return "redirect:findAll.do";
}
/**
* 根据roleId查询role,并查询出可以添加的权限
* @param roleId
* @return
* @throws Exception
*/
@RequestMapping("/findRoleByIdAndAllPermission.do")
public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id", required = true) String roleId) throws Exception {
ModelAndView mv = new ModelAndView();
//根据roleId查询role
Role role = roleService.findById(roleId);
System.out.println("角色:" + role);
//根据roleId查询可以添加的权限
List<Permission> otherPermissions = roleService.findOtherPermissions(roleId);
System.out.println("权限:" + otherPermissions);
mv.addObject("role", role);
mv.addObject("permissionList", otherPermissions);
mv.setViewName("role-permission-add");
return mv;
}
}
逻辑层:
package com.hz.service.impl;
import com.hz.dao.IRoleDao;
import com.hz.domain.Permission;
import com.hz.domain.Role;
import com.hz.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 3:47
*/
@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
@Autowired
private IRoleDao roleDao;
/**
* 查询所有角色
* @return
* @throws Exception
*/
@Override
public List<Role> findAll() throws Exception {
return roleDao.findALl();
}
/**
* 添加角色
* @param role
* @return
* @throws Exception
*/
@Override
public void save(Role role) throws Exception {
// 不好的设计
Integer roleId = (int) (Math.random() * Math.random() * Math.random() * 100000);
role.setId(roleId.toString());
roleDao.save(role);
}
/**
* 角色详情查询
* @param roleId
* @return
* @throws Exception
*/
@Override
public Role findById(String roleId) throws Exception {
return roleDao.findById(roleId);
}
/**
* 根据角色Id删除角色
* @param roleId
* @return
* @throws Exception
*/
@Override
public void deleteRoleById(String roleId) {
roleDao.deleteRoleById(roleId);
}
/**
* 给角色添加权限
* @param roleId
* @param permissionIds
* @return
* @throws Exception
*/
@Override
public void addPermissionToRole(String roleId, String[] permissionIds) {
for(String permissionId:permissionIds){
roleDao.addPermissionToRole(roleId,permissionId);
}
}
/**
* 根据roleId查询role,并查询出可以添加的权限
* @param roleId
* @return
* @throws Exception
*/
@Override
public List<Permission> findOtherPermissions(String roleId) {
return roleDao.findOtherPermissions(roleId);
}
}
dao层:
package com.hz.dao;
import com.hz.domain.Permission;
import com.hz.domain.Role;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 3:50
*/
public interface IRoleDao {
/**
* 查询所有角色
* @return
* @throws Exception
*/
@Select("select * from role")
List<Role> findALl() throws Exception;
/**
* 添加角色
* @param role
* @return
* @throws Exception
*/
@Insert("insert into role(id,roleName,roleDesc) values(#{id},#{roleName},#{roleDesc})")
void save(Role role) throws Exception;
/**
* 角色详情查询
* @param roleId
* @return
* @throws Exception
*/
@Select("select * from role where id=#{roleId}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "roleName", column = "roleName"),
@Result(property = "roleDesc", column = "roleDesc"),
@Result(property = "permissions", column = "id", javaType = java.util.List.class, many = @Many(select = "com.hz.dao.IPermissionDao.findPermissionByRoleId"))})
Role findById(String roleId) throws Exception;
/**
* 根据角色Id删除角色
* @param roleId
* @return
* @throws Exception
*/
@Delete("delete from role where id=#{roleId}")
void deleteRoleById(String roleId);
/**
* 给角色添加权限
* @param roleId
* @param
* @return
* @throws Exception
*/
@Insert("insert into role_permission(roleId,permissionId) values(#{roleId},#{permissionId})")
void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permissionId);
/**
* 根据roleId查询role,并查询出可以添加的权限
* @param roleId
* @return
* @throws Exception
*/
@Select("select * from permission where id not in (select permissionId from role_permission where roleId=#{roleId})")
List<Permission> findOtherPermissions(String roleId);
// 根据用户id查询出所有对应的角色
@Select("select * from role where id in (select roleId from users_role where userId=#{userId})")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "roleName", column = "roleName"),
@Result(property = "roleDesc", column = "roleDesc"),
@Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.hz.dao.IPermissionDao.findPermissionByRoleId"))
})
List<Role> findRoleByUserId(String userId) throws Exception;
}
最后就是资源管理控制部分了
二话不说,直接上代码:
接口层:
package com.hz.controller;
import com.hz.domain.Permission;
import com.hz.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 4:40
*/
@Controller
@RequestMapping("/permission")
public class PermissionController {
@Autowired
private IPermissionService permissionService;
/**
* 删除资源
* @param id
* @return
* @throws Exception
*/
@RequestMapping("/deletePermission")
public String deletePermission(String id) throws Exception {
permissionService.deleteById(id);
return "redirect:findAll.do";
}
/**
* 根据id查看资源详情
* @param id
* @return
* @throws Exception
*/
@RequestMapping("/findById")
public ModelAndView findById(String id) throws Exception {
Permission permission= permissionService.findById(id);
ModelAndView mv=new ModelAndView();
mv.setViewName("permission-show");
mv.addObject("permission",permission);
return mv;
}
/**
* 保存
* @param permission
* @return
* @throws Exception
*/
@RequestMapping("/save.do")
public String save(Permission permission) throws Exception {
permissionService.save(permission);
return "redirect:findAll.do";
}
/**
* 查询所有资源列表
* @return
* @throws Exception
*/
@RequestMapping("/findAll.do")
public ModelAndView findAll() throws Exception {
ModelAndView mv=new ModelAndView();
List<Permission> permissionList = permissionService.findAll();
mv.addObject("permissionList",permissionList);
mv.setViewName("permission-list");
return mv;
}
}
逻辑层:
package com.hz.service.impl;
import com.hz.dao.IPermissionDao;
import com.hz.domain.Permission;
import com.hz.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 4:41
*/
@Service
@Transactional
public class PermissionImpl implements IPermissionService {
@Autowired
private IPermissionDao permissionDao;
/**
* 删除资源
* @param id
* @return
* @throws Exception
*/
@Override
public void deleteById(String id) throws Exception {
permissionDao.deleteFromRole_Permission(id);
permissionDao.deleteById(id);
}
@Override
public Permission findById(String id) throws Exception {
return permissionDao.findById(id);
}
@Override
public void save(Permission permission) throws Exception{
// 不好的设计
Integer permissionId = (int) (Math.random() * Math.random() * Math.random() * 100000);
permission.setId(permissionId.toString());
permissionDao.save(permission);
}
@Override
public List<Permission> findAll() throws Exception{
return permissionDao.findAll();
}
}
dao层:
package com.hz.dao;
import com.hz.domain.Permission;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author hz
* @date 2020/4/9 4:42
*/
public interface IPermissionDao {
/**
* 查询所有资源
* @return
*/
@Select("select * from permission")
List<Permission> findAll();
/**
* 根据id查询资源详情
* @param id
* @return
*/
@Select("select * from permission where id=#{id}")
Permission findById(String id);
/**
* 增加资源
* @param permission
*/
@Insert("insert into permission(id,permissionName,url) values(#{id},#{permissionName},#{url})")
void save(Permission permission);
/**
* 根据id删除资源
* @param id
*/
@Delete("delete from permission where id=#{id}")
void deleteById(String id);
/**
* 根据id删除资源和角色
* @param id
*/
@Delete("delete from role_permission where permissionId=#{id}")
void deleteFromRole_Permission(String id);
// 查询与role关联的所有的权限
@Select("select * from permission where id in (select permissionId from role_permission where roleId=#{id} )")
List<Permission> findPermissionByRoleId(String id) throws Exception;
}
大致过程实现与思路就是这样了:有兴趣的小伙伴可以加入我的死人交流群一起学习和交流:
QQ群947405150