权限资源管理
- 在demo15的基础上开发
# 使用注解控制权限,所以需要在security配置类上开启配置;否则注解不生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
-
查看数据库,test用户拥有的角色权限为普通管理员;普通管理员拥有的权限资源为28
-
访问接口http://localhost/permission/list,跳转到403页面
-
将普通管理员拥有的权限资源修改为29,在次测试,获取成功
-
代码实现
# 控制层
@Controller
@RequestMapping("/permission")
public class SysPermissionController {
private static final String HTML_PREFIX = "system/permission/";
// 跳转到分页查询页面
@PreAuthorize("hasAuthority('sys:permission')")
@GetMapping(value = {"/", ""})
public String permission() {
return HTML_PREFIX + "permission-list";
}
// 业务层对象
@Autowired
private SysPermissionService sysPermissionService;
// 查询所有权限资源
@PreAuthorize("hasAuthority('sys:permission:list')")
@GetMapping("/list")
@ResponseBody
public MengxueguResult list() {
// MyBatis-plus已经提供的,查询SysPermission表中的所有记录
List<SysPermission> list = sysPermissionService.list();
return MengxueguResult.ok(list);
}
/**
* 跳转新增或者修改页面
* /form 新增
* /form/{id} 修改
* @PathVariable(required = false) 设置为false,则id可传也可不传,不然报500
* @return
*/
@PreAuthorize("hasAnyAuthority('sys:permission:edit', 'sys:permission:add')")
@GetMapping(value = {"/form", "/form/{id}"})
public String form(@PathVariable(required = false) Long id, Model model) {
// 1. 通过权限id查询对应权限信息
SysPermission permission = sysPermissionService.getById(id);
// 绑定后页面可获取
model.addAttribute("permission", permission == null ? new SysPermission() : permission);
return HTML_PREFIX + "permission-form";
}
/**
* 提交新增或修改的数据
* @param permission
* @return
*/
@PreAuthorize("hasAnyAuthority('sys:permission:edit', 'sys:permission:add')")
@RequestMapping(value="", method = {RequestMethod.PUT, RequestMethod.POST})
public String saveOrUpdate(SysPermission permission) {
sysPermissionService.saveOrUpdate(permission);
return "redirect:/permission";
}
/**
* 删除权限资源,及其权限资源下的子资源
* @param id
* @return
*/
@PreAuthorize("hasAuthority('sys:permission:delete')")
@DeleteMapping("/{id}")
@ResponseBody
public MengxueguResult deleteById(@PathVariable("id") Long id) {
sysPermissionService.deleteById(id);
return MengxueguResult.ok();
}
}
# 业务层接口
public interface SysPermissionService extends IService<SysPermission> {
/**
* 通过权限id删除权限资源
* @param id
* @return
*/
boolean deleteById(Long id);
}
# 业务层实现
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {
@Transactional
@Override
public boolean deleteById(Long id) {
// 1. 删除当前id的权限
baseMapper.deleteById(id);
// 2. 删除parent_id = id 的权限, 删除当前点击的子权限
LambdaQueryWrapper<SysPermission> queryWrapper = new LambdaQueryWrapper();
//delete from sys_permission where parent_id = #{id};
queryWrapper.eq(SysPermission::getParentId, id);
baseMapper.delete(queryWrapper);
return true;
}
}