直接上代码:
hasRole方法的实现类:
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方法的实现类:
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(); }}
剩余方法的实现方式与上面一样,在这省略......
然后写一个全局Interceptor: ShiroFreeMarkerInterceptor
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中配置拦截器:
public void configInterceptor(Interceptors me) { me.add(new ShiroInterceptor()); me.add(new ShiroFreeMarkerInterceptor()); }
页面中使用方式:
<#if hasAnyRoles("admin","user")> <#if hasRole("admin")>