自定义(补充)shiro标签

shiro提供了jsp标签用于页面上的权限控制,有hasAnyRoles,hasPermission等标签,但是却没提供hasAnyPermission标签,有点不大方便。

这时候我们完全可以仿照shiro的源码,进行照猫画虎,扩充一下。

shiro的标签定义文件在shiro-all.jar下的META-INF目录下的shiro.tld中,打开文件后我们可以看到如下标签的定义:


  1.1.2
  1.2
  Apache Shiro
  http://shiro.apache.org/tags
  Apache Shiro JSP Tag Library.
  
    hasPermission
    org.apache.shiro.web.tags.HasPermissionTag
    JSP
    Displays body content only if the current Subject (user)
      'has' (implies) the specified permission (i.e the user has the specified ability).
    
    
      name
      true
      true
    
  
  
    hasAnyRoles
    org.apache.shiro.web.tags.HasAnyRolesTag
    JSP
    Displays body content only if the current user has one of the specified roles from a
      comma-separated list of role names.
    
    
      name
      true
      true
    
  
该文件中定义了每个标签的名字和相应的标签的实现类。我们要补充一个hasAnyPermission的标签,该标签的逻辑和hasAnyRoles有些类似。我们先打开hasAnyRoles的实现类看看,然后照猫画虎做一个hasAnyPermission的标签。

package org.apache.shiro.web.tags;
import org.apache.shiro.subject.Subject;
public class HasAnyRolesTag extends RoleTag {
    private static final String ROLE_NAMES_DELIMETER = ",";
    public HasAnyRolesTag() {
    }
    protected boolean showTagBody(String roleNames) {
        boolean hasAnyRole = false;
        Subject subject = getSubject();
        if (subject != null) {
            for (String role : roleNames.split(ROLE_NAMES_DELIMETER)) {
                if (subject.hasRole(role.trim())) {
                    hasAnyRole = true;
                    break;
                }
            }
        }
        return hasAnyRole;
    }
}

以上是hasAnyRolesTag的实现类,我们仿照这个实现hasAnyPermission:

package org.apache.shiro.web.tags;
import org.apache.shiro.subject.Subject;
public class HasAnyPermissionTag extends PermissionTag {
	private static final long serialVersionUID = 1L;
	private static final String PERMISSION_NAMES_DELIMETER = ",";
	public HasAnyPermissionTag() {
	}
	@Override
	protected boolean showTagBody(String permissions) {
		boolean hasAnyPermission = false;
		Subject subject = getSubject();
		if (subject != null) {
			for (String permission : permissions
					.split(PERMISSION_NAMES_DELIMETER)) {
				if (subject.isPermitted(permission.trim())) {
					hasAnyPermission = true;
					break;
				}
			}
		}
		return hasAnyPermission;
	}
}


将该源代码编译成class字节码文件,扔进jar包的\org\apache\shiro\web\tags目录下
并在jar包里的shiro.tld文件中加入以下代码指定标签:

  
    hasAnyPermission
    org.apache.shiro.web.tags.HasAnyPermissionTag
    JSP
    Displays body content only if the current Subject (user)
      'has' (implies) one of the specified permission (i.e the user has the specified ability) form a list of permissions.
    
    
      name
      true
      true
    
  


OK,搞定,到页面上测试一下:


	
  • 系统配置

  • 表示如果当前用户拥有以下权限的任何一个权限,那么该菜单就会显示,好的,可以了。

    收工。


    你可能感兴趣的:(web开发,shiro)