自定义(补充)shiro标签

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

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

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

[html] view plain copy

  1. 1.1.2
  2. 1.2
  3. Apache Shiro
  4. http://shiro.apache.org/tags
  5. Apache Shiro JSP Tag Library.
  6. hasPermission
  7. org.apache.shiro.web.tags.HasPermissionTag
  8. JSP
  9. Displays body content only if the current Subject (user)
  10. 'has' (implies) the specified permission (i.e the user has the specified ability).
  11. name
  12. true
  13. true
  14. hasAnyRoles
  15. org.apache.shiro.web.tags.HasAnyRolesTag
  16. JSP
  17. Displays body content only if the current user has one of the specified roles from a
  18. comma-separated list of role names.
  19. name
  20. true
  21. true

该文件中定义了每个标签的名字和相应的标签的实现类。我们要补充一个hasAnyPermission的标签,该标签的逻辑和hasAnyRoles有些类似。我们先打开hasAnyRoles的实现类看看,然后照猫画虎做一个hasAnyPermission的标签。

[java] view plain copy

  1. package org.apache.shiro.web.tags;
  2. import org.apache.shiro.subject.Subject;
  3. public class HasAnyRolesTag extends RoleTag {
  4. private static final String ROLE_NAMES_DELIMETER = ",";
  5. public HasAnyRolesTag() {
  6. }
  7. protected boolean showTagBody(String roleNames) {
  8. boolean hasAnyRole = false;
  9. Subject subject = getSubject();
  10. if (subject != null) {
  11. for (String role : roleNames.split(ROLE_NAMES_DELIMETER)) {
  12. if (subject.hasRole(role.trim())) {
  13. hasAnyRole = true;
  14. break;
  15. }
  16. }
  17. }
  18. return hasAnyRole;
  19. }
  20. }

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

[java] view plain copy

  1. package org.apache.shiro.web.tags;
  2. import org.apache.shiro.subject.Subject;
  3. public class HasAnyPermissionTag extends PermissionTag {
  4. private static final long serialVersionUID = 1L;
  5. private static final String PERMISSION_NAMES_DELIMETER = ",";
  6. public HasAnyPermissionTag() {
  7. }
  8. @Override
  9. protected boolean showTagBody(String permissions) {
  10. boolean hasAnyPermission = false;
  11. Subject subject = getSubject();
  12. if (subject != null) {
  13. for (String permission : permissions
  14. .split(PERMISSION_NAMES_DELIMETER)) {
  15. if (subject.isPermitted(permission.trim())) {
  16. hasAnyPermission = true;
  17. break;
  18. }
  19. }
  20. }
  21. return hasAnyPermission;
  22. }
  23. }

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

[html] view plain copy

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

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

[html] view plain copy

  1. 系统配置

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

收工。

你可能感兴趣的:(自定义(补充)shiro标签)