直接上代碼: html
hasRole方法的實現類:java
public class HasRoleFreeMarkerMethod implements TemplateMethodModel{ @SuppressWarnings("rawtypes") @Override public Object exec(List list) throws TemplateModelException { if(null == list || 1 != list.size()){ throw new TemplateModelException("Wrong arguments: only one argument is allowed"); } String roleName = (String) list.get(0); return getSubject() != null && roleName != null && roleName.length() > 0 && getSubject().hasRole(roleName); } private static Subject getSubject() { return SecurityUtils.getSubject(); } }
hasAnyRoles方法的實現類:ide
public class HasAnyRolesFreeMarkerMethod implements TemplateMethodModel{ @SuppressWarnings("rawtypes") @Override public Object exec(List list) throws TemplateModelException { //參數不合法直接返回false if(null == list || list.isEmpty()){ return false; } // 循環判斷當前用用戶是否擁有其中的某一個角色 boolean hasAny = false; for(Object obj : list){ System.out.println(obj); if(getSubject().hasRole((String)obj)){ hasAny = true; break; } } return hasAny; } private static Subject getSubject() { return SecurityUtils.getSubject(); } }
剩餘方法的實現方式與上面同樣,在這省略......code
而後寫一個全局Interceptor: ShiroFreeMarkerInterceptorhtm
public class ShiroFreeMarkerInterceptor implements Interceptor { public void intercept(ActionInvocation 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(); } }
在JFinal中配置攔截器:
get
public void configInterceptor(Interceptors me) { me.add(new ShiroInterceptor()); me.add(new ShiroFreeMarkerInterceptor()); }
頁面中使用方式:input
<#if hasAnyRoles("admin","user")> <input type="button" value="查看"/> </#if> <#if hasRole("admin")> <input type="button" value="編輯"/> </#if>