博客项目目录: 请戳这里
准备
需求:用户登录后,进入自己发表的文章,点击删除,即可删除帖子,除此之外,设置一个超级管理员,管理员除了能删除帖子,还有置顶和加精的权限
1.修改detail.ftl
#--发布者删除-->
<#if post.userId == profile.id>
<span class="layui-btn layui-btn-xs jie-admin" type="del">删除</span>
</#if>
2.修改jie.js
controller层请求过来,触发fly.json(),然后跳转到/user/index页面
3.添加controller层普通用户删除
首先获取对应文章,断定帖子是否被删除,以及是否有权限。然后分别从文章表,消息表和收藏表删除帖子,删除完成之后,跳转到用户首页
//普通用户删除帖子
@ResponseBody
@Transactional
@PostMapping("/post/delete")
public Result delete(Long id) {
Post post = postService.getById(id);
Assert.notNull(post, "该帖子已被删除");
Assert.isTrue(post.getUserId().longValue() == getProfileId().longValue(), "无权限删除此文章!");
postService.removeById(id);
// 删除相关消息、收藏等
messageService.removeByMap(MapUtil.of("post_id", id));
collectionService.removeByMap(MapUtil.of("post_id", id));
return Result.success().action("/user/index");
}
4.普通用户删除测试
点击删除按钮:
跳转到用户首页:
点击本周热议部分刚才删除的帖子:
5.设置超级管理员
首先获取账户信息,如果id为7,则赋予超级管理员角色
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
AccountProfile profile = (AccountProfile) principals.getPrimaryPrincipal();
// 给id为7的admin赋予admin角色
if(profile.getId() == 7) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRole("admin");
return info;
}
return null;
}
6.修改detail.ftl
管理员除了有删除操作,还有置顶、加精相关操作。
lelve为0,执行置顶操作,rank变为1;level大于0,执行取消置顶操作,rank由1变为0。
recommend为false,执行加精操作,rank变为1;recommend为true,执行取消加精操作,rank由1变为0.
<#--管理员操作-->
<@shiro.hasRole name="admin">
<span class="layui-btn layui-btn-xs jie-admin" type="set" field="delete" rank="1">删除</span>
<#if post.level == 0><span class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="1">置顶</span></#if>
<#if post.level gt 0><span class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="0" style="background-color:#ccc;">取消置顶</span></#if>
<#if !post.recommend><span class="layui-btn layui-btn-xs jie-admin" type="set" field="status" rank="1">加精</span></#if>
<#if post.recommend><span class="layui-btn layui-btn-xs jie-admin" type="set" field="status" rank="0" style="background-color:#ccc;">取消加精</span></#if>
</@shiro.hasRole>
7.添加controller层管理员操作
首先获取帖子,断定帖子是否被删除。然后根据字段类型,进行操作。
如果field是"delete",则直接删除。
如果field是"status",执行加精操作,将rank设为1。
如果field是"stick",执行置顶操作,如果rank是0,说明按钮处显示置顶,实际上处于取消置顶状态,此时将level置为0,触发置顶操作。
@ResponseBody
@PostMapping("/jie-set")
public Result jetSet(Long id, Integer rank, String field) {
Post post = postService.getById(id);
Assert.notNull(post, "该帖子已被删除");
if("delete".equals(field)) {
postService.removeById(id);
return Result.success();
} else if("status".equals(field)) {
post.setRecommend(rank == 1);
} else if("stick".equals(field)) {
post.setLevel(rank);
}
postService.updateById(post);
return Result.success();
}
8.修改jie.js
9.测试
管理员置顶:
管理员加精:
管理员删除:
参考资料:
https://github.com/MarkerHub/eblog