池州商城网站开发,在线个人网页生成,响应式网站案例,网站设计模板 优帮云概述在学习注解的时候#xff0c;学了个懵懵懂懂。学了JavaWeb之后#xff0c;在做Demo项目的过程中#xff0c;借助注解和反射实现了对页面按钮的权限控制#xff0c;对于注解才算咂摸出了点味儿来。需求以角色列表页面为例#xff0c;该页面包含新建学了个懵懵懂懂。学了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(); // ServletNameString action(); // ActionName, 每个action是Servlet中的一个方法代表一个请求地址servletName?actionactionNameString 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?actionindex// 该页面包含新建编辑启用/禁用删除四个权限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 getButtonPermissions(Method method) {// buttonMap是一个以Button.name为key, 以是否有权限的布尔值为value的键值对// 该结果会被保存在requestScope中供jsp页面使用Map 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文件中控制按钮是否显示新建角色