Java注解权限应用

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

  首先思路是

  用户登录 获得权限列表 存在加密cookie session什么的

  方法用注解修饰 不通的权限有不同的修饰参数

  @Target(ElementType.METHOD)

  @Retention(RetentionPolicy.RUNTIME)

  @interface AnnotationVerify {

  /**

  * to verify code,

  * 定义参数

  * @return

  */

  public String code();

  }

  public class SomeAction {

  @AnnotationVerify(code = “ADMIN,user”)

  public static List<String> sayHello(String name,int sex) {

  System.out.println(“————hello ——“+name);

  List<String> l=new ArrayList<String>();

  l.add(“Accept”);

  l.add(“PassAccept”);

  return l;

  }

  @AnnotationVerify(code = “ADMIN”)

  public static void sayHelloWorld() {

  System.out.println(“———admin———“);

  }

  public static void main(String[] args) throws Exception {

  SomeAction s = new SomeAction();

  //代理 获得结果

  Map<String,Object> resultMap = s.invoke(s,”sayHello”,new Object[]{“赵天明”,1});

  //判读是否成功 验证权限

  if (resultMap.get(“success”).equals(Boolean.TRUE)) {

  System.out.println(“执行成功! 结果”);

  System.out.println(resultMap.get(“result”));

  } else {

  System.out.println(“没有权限!”);

  }

  }

  /**

  * 验证方法权限 并且执行invoke结果

  * @param Object proxy

  * @param String methodName

  * @param Object[] methodParams

  * @return Map

  * @throws Exception

  */

  public Map<String,Object> invoke(Object proxy, String methodName, Object[] methodParams)

  throws Exception {

  Map<String,Object> resultMap=new HashMap<String,Object>();

  Method method = getMethod(proxy.getClass(), methodName);

  String verfiyCode = getMethodAnnotation(method);

  if (Verfiy(verfiyCode)) {

  Object resultObject=method.invoke(proxy, methodParams);

  resultMap.put(“success”,true);

  resultMap.put(“result”,resultObject);

  return resultMap;

  } else {

  resultMap.put(“success”,false);

  return resultMap;

  }

  }

  /**

  * 验证权限

  * @param code

  * @return

  */

  public boolean Verfiy(String code) {

  String[] codes=code.split(“,”);

  for (VerfiyCode v : VerfiyCode.values()) {

  for(String c:codes){

  if (v.name().equals(c))

  return true;

  }

  }

  return false;

  }

  /**

  * 获得方法

  * @param aClass

  * @param methodName

  * @return

  */

  public Method getMethod(Class<? extends Object> aClass, String methodName) {

  Method[] methods = aClass.getDeclaredMethods();

  for (Method method : methods) {

  if (method.getName().equals(methodName)) {

  return method;

  }

  }

  return null;

  }

  /**

  * 获得方法注解信息

  * @param method

  * @return

  */

  public String getMethodAnnotation(Method method) {

  AnnotationVerify annotation = method

  .getAnnotation(AnnotationVerify.class);

  if (annotation != null) {

  return annotation.code();

  }

  return null;

  }

  }

  /**

  * 权限类

  * @author XiaoMing

  *

  */

  enum VerfiyCode {

  ADMIN, USER,

  }

你的选择是做或不做,但不做就永远不会有机会

Java注解权限应用

相关文章:

你感兴趣的文章:

标签云: