以前在寫某項目的時候,由於要進行到權限驗證,並且頁面是後端進行渲染的,因此我就要在輸出的頁面進行對應的權限顯示,可是卻發現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