我们知道如果是采用jsp视图引擎,直接在jsp中加入shiro的tag就可以,然而在thymeleaf视图引擎下,并未有shiro的tag lib。实际上目前shiro+Thymeleaf的html页面中shiro标签方式验证已经有人实现了并将代码用法放到了github上,具体请参考:《thymeleaf-extras-shiro》。
下边将结合《thymeleaf-extras-shiro》与springmvc集成实现thymeleaf中html中加验证shiro验证标签的用法进行讲解,具体内容分为以下几部分:
1)引入依赖
2)需要修改哪些配置?
3)如何使用?
1)引入依赖
引入thymeleaf-extras-shiro依赖到pom中
com.github.theborakompanioni
thymeleaf-extras-shiro
${thymeleaf-shiro.version}
上边${thymeleaf-shiro.version}是thymelef-extras-shiro的版本,目前最新版本是2.0.0。
2)修改配置
2.1)xml方式配置
需要在springmvc-servlet.xml配置文件中引入thymeleaf依赖外,需要在templateEngine bean下设置additionalDialects属性:
注意:这个dialect是核心配置,缺少这个thymeleaf页面中的标签将无法解析。
2.2)SpringMVC或者SpringBoot注解方式配置
@BeanpublicSpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine= newSpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
Set additionalDialects = new HashSet();
additionalDialects.add(newShiroDialect());
templateEngine.setAdditionalDialects(additionalDialects);returntemplateEngine;
}
3)在thymeleaf的html页面中使用shiro验证标签
3.1)在html文件头的标签做修改
Example
thymeleaf-extras-shiroPlease login
Hello,, how are you today?
3.2)html标签(例如:a/tr/td/p等) shiro:hasPermission="article:query" 标签使用
The guest tag
PleaseLogin
The user tag
Welcome back John! Not John? Clickhereto login.
The authenticated tag
Update your contact information
The notAuthenticated tag
Pleaseloginin order to update your credit card information.
The principal tag
Hello, , how are you today?
or
Hello, , how are you today?
Typed principal and principal property are also supported.
The hasRole tag
Administer the system
The lacksRole tag
Sorry, you are not allowed to administer the system.
The hasAllRoles tag
You are a developer and a project manager.
The hasAnyRoles tag
You are a developer, project manager, or administrator.
The hasPermission tag
Create a new User
The lacksPermission tag
Sorry, you are not allowed to delete user accounts.
The hasAllPermissions tag
You can create and delete users.
The hasAnyPermissions tag
You can create or delete users.
3.3)和jsp页面一样的shiro:hasPermission标签使用
实际上和Jsp页面中的验证标签一致,而且与上边基本一致,去掉html标签改写为:
test
3.4)javascript中使用hasPermission标签
需要自定义@Component,例如:
packagecom.dx.test.shiro;importorg.apache.shiro.SecurityUtils;importorg.springframework.stereotype.Component;/*** js调用 thymeleaf 实现按钮权限*/@Component("perms")public classPermsService
{public booleanhasPerm(String permission)
{returnSecurityUtils.getSubject().isPermitted(permission);
}
}
其需要在applicationContext-*.xml中,添加扫描包组件确保能扫描到该包:
Js中使用示例:
var editFlag = "[[${@perms.hasPerm('user:edit')}]]";var deleteFlag = "[[${@perms.hasPerm('user:delete')}]]";var assignRoleFlag="[[${@perms.hasPerm('user:assignRole')}]]";//其他业务