Spring Boot Thymeleaf中使用Shiro标签
在《Spring-Boot-shiro权限控制》中,当用户访问没有权限的资源时,我们采取的做法是跳转到403页面,但在实际项目中更为常见的做法是只显示当前用户拥有访问权限的资源链接。配合Thymeleaf中的Shiro标签可以很简单的实现这个目标。实际上Thymeleaf官方并没有提供Shiro的标签,我们需要引入第三方实现,地址为https://github.com/theborakompani
在《Spring-Boot-shiro权限控制》中,当用户访问没有权限的资源时,我们采取的做法是跳转到403页面,但在实际项目中更为常见的做法是只显示当前用户拥有访问权限的资源链接。配合Thymeleaf中的Shiro标签可以很简单的实现这个目标。
实际上Thymeleaf官方并没有提供Shiro的标签,我们需要引入第三方实现,地址为https://github.com/theborakompanioni/thymeleaf-extras-shiro。
引入thymeleaf-extras-shiro
在pom中引入:
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
ShiroConfig配置
引入依赖后,需要在ShiroConfig中配置该方言标签:
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
首页改造
更改index.html,用于测试Shiro标签的使用:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro" >
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<p>你好![[${user.userName}]]</p>
<p shiro:hasRole="admin">你的角色为超级管理员</p>
<p shiro:hasRole="test">你的角色为测试账户</p>
<div>
<a shiro:hasPermission="user:user" th:href="@{/user/list}">获取用户信息</a>
<a shiro:hasPermission="user:add" th:href="@{/user/add}">新增用户</a>
<a shiro:hasPermission="user:delete" th:href="@{/user/delete}">删除用户</a>
</div>
<a th:href="@{/logout}">注销</a>
</body>
</html>
值得注意的是,在html页面中使用Shiro标签需要给html标签添加xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
。
测试
启动项目,使用mrbird(角色为admin,具有user:user,user:add,user:delete权限)账户登录:
使用tester(角色为tester,仅有user:user权限)账户登录:
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)