Freemarker自定義標籤彌補Shiro沒有HasAnyPermissions缺陷

前言

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

而後在有須要的地方調用便可:bash

hasAnyPermissions('user:save','user:list')?c=='true'複製代碼

原文連接:www.licoy.cn/2952.htmlide

相關文章
相關標籤/搜索