以前在写某项目的时候,由于要进行到权限验证,并且页面是后端进行渲染的,因此我就要在输出的页面进行对应的权限显示,可是却发现Shiro标签中只有hasAnyRole
这个标签,却没有对应的HasAnyPermissions
,后来通过一些折腾,使用Freemarker自定义标签达到了这个效果。html
首先,先新建一个HasAnyPermissions
类,并继承freemarker的TemplateMethodModelEx
类,而后再使用shiro的checkPermission来循环验证是否包含传入的权限组的所有权限,代码以下:apache
/** * @author licoy.cn * @version 2017/9/11 */ public class HasAnyPermissions implements TemplateMethodModelEx { @Override public Object exec(List list) throws TemplateModelException { if(list.size()<=0){ throw new TemplateModelException("HasAnyPermissions - 错误参数"); } org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject(); int index = 0; for (Object s : list){ index++; SimpleScalar str = (SimpleScalar ) s; try { subject.checkPermission(str.getAsString()); }catch (Exception e){ if(index==list.size()){ return false; } continue; } return true; } return false; } }
在ftl页面中自定义变量:后端
<#assign hasAnyPermissions = "xxx.config.freemarker.HasAnyPermissions"?new()>;
而后在有须要的地方调用便可:ide
hasAnyPermissions('user:save','user:list')?c=='true'
原文连接:https://www.licoy.cn/2952.htmlcode