實現在FreeMarker模板中控制對應按鈕的顯示隱藏主要用到了Shiro中的hasRole, hasAnyRoles, hasPermission以及Authenticated等方法,我們可以實現TemplateMethodModelEx類的相關操作,然后通過全局攔截器將對應的方法注入到視圖模板中,就可以直接在ftl模板中使用自定義的方法進行判斷了,具體代碼如下:
第一步實現 HasPermissionFreeMarkerMethod
public class HasPermissionFreeMarkerMethod implements TemplateMethodModelEx { @Override public Object exec(List list) throws TemplateModelException { if (null == list || 1 != list.size()) { throw new TemplateModelException("Wrong arguments: only one argument is allowed"); } Object permissionName = list.get(0); return getSubject() != null && permissionName != null && getSubject().isPermitted(permissionName.toString()); } private static Subject getSubject() { return SecurityUtils.getSubject(); } }
第二步定義一個全局的攔截器
public class ShiroFreeMarkerInterceptor implements Interceptor { @Override public void intercept(Invocation ai) { Controller c = ai.getController(); c.setAttr("hasRole", new HasRoleFreeMarkerMethod()); //c.setAttr("hasAnyRoles", new HasAnyRolesFreeMarkerMethod()); c.setAttr("hasPermission", new HasPermissionFreeMarkerMethod()); //c.setAttr("isAuthenticated", new AuthenticatedFreeMarkerMethod()); // 執行正常邏輯 ai.invoke(); } }
第三步在AppConfig中配置全局攔截器
/** * 配置全局攔截器 */ public void configInterceptor(Interceptors me) { me.add(new ShiroInterceptor()); me.add(new AuthInterceptor()); me.add(new ShiroFreeMarkerInterceptor());//添加在FreeMarker視圖中使用Shiro的攔截器 }
現在我們就可以在視圖中直接來根據權限標識控制按鈕的顯示與隱藏了
<#if hasPermission("Trade:新增")> <a class="btn_color_1" onclick="onEdit(0)"><i class="fa fa-plus"></i> 新增</a> </#if> <#if hasPermission("Trade:編輯")> <a class="btn_color_2" onclick="onEdit()"><i class="fa fa-edit"></i> 編輯</a> </#if> <#if hasPermission("Trade:刪除")> <a class="btn_color_3" onclick="onDelete()"><i class="fa fa-remove"></i> 刪除</a> </#if> <#if hasPermission("Trade:重新統計")> <a class="btn_color_2" onclick="onTongJi()"><i class="fa fa-bolt"></i> 重新統計</a> </#if>