记录Java注解在JavaWeb中的一个应用实例

概述

在学习注解的时候,学了个懵懵懂懂。学了JavaWeb之后,在做Demo项目的过程中,借助注解和反射实现了对页面按钮的权限控制,对于注解才算咂摸出了点味儿来。

需求

以"角色列表"页面为例,该页面包含"新建","编辑","启用/禁用","删除"四个权限。根据用户所属角色的权限,来控制这些按钮是否显示。问题是,如何确定哪些页面下包含哪些按钮?

实现

定义注解

package com.ttpfx.bean;

import java.lang.annotation.*;

@Target(ElementType.METHOD) // 注解的作用对象:只能用于方法
@Retention(RetentionPolicy.RUNTIME) // 注解的级别:运行时有效,可以通过反射获取注解信息
@Repeatable(Buttons.class) // 可重复注解: 一个方法可以有多个Button注解,一个方法的多个Button注解将组成一个Buttons返回
public @interface Button {
    String servlet(); // ServletName
    String action(); // ActionName, 每个action是Servlet中的一个方法,代表一个请求地址:servletName?action=actionName
    String name(); // 按钮名称
}
package com.ttpfx.bean;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Buttons {
    Button[] value(); // Button注解的数组,通过Btuuons.value()获取页面的多个Button
}

在Servlet中使用注解

public class RoleServlet extends BaseServlet {
    private RoleService roleService = new RoleServiceImpl();

    // RoleServlet.index() 对应角色列表页面,访问地址为:/role?action=index 
    // 该页面包含"新建","编辑","启用/禁用","删除"四个权限
    @Button(servlet = "role", action = "add", name = "add")
    @Button(servlet = "role", action = "edit", name = "edit")
    @Button(servlet = "role", action = "changeStatus", name = "changeStatus")
    @Button(servlet = "role", action = "delete", name = "delete")
    protected void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // ....
    }
}

在BaseServlet中校验页面按钮的权限,并将结果保存在requestScope中

// method:Servlet中的方法, 如上面RoleServlet.index()
private Map<String, Boolean> getButtonPermissions(Method method) {
    // buttonMap是一个以Button.name为key, 以是否有权限的布尔值为value的键值对
    // 该结果会被保存在requestScope中,供jsp页面使用
    Map<String, Boolean> buttonMap = new HashMap<>();

    Button[] buttonAnnotations = null;

    // 页面有一个Button注解的时候可以直接获取
    // 页面有多个Button注解的时候,只能获取到Buttons注解,再通过Buttons.value()方法得到多个Button注解
    Buttons buttonsAnnotation = method.getAnnotation(Buttons.class);
    Button buttonAnnotation = method.getAnnotation(Button.class);
    if (buttonsAnnotation != null) {
        buttonAnnotations = buttonsAnnotation.value();
    } else if (buttonAnnotation != null){
        buttonAnnotations = new Button[] {buttonAnnotation};
    }

    if (buttonAnnotations != null) {
        for (Button button : buttonAnnotations) {
            // 在这里实现对每个按钮的权限验证,将结果put至buttonMap
            // 真正的验证过程已省略
            buttonMap.put(button.name, true);
        }
    }

    return buttonMap;
}

在页面的jsp文件中,控制按钮是否显示

<c:if test="${requestScope.buttonMap.add}">
      <button type="button">新建角色</button>
</c:if>
posted @ 2020-10-29 17:22  ttpfx  阅读(113)  评论(0)    收藏  举报