关于springboot:SpringBoot系列3AOP实战1权限日志

36次阅读

共计 4683 个字符,预计需要花费 12 分钟才能阅读完成。

摘要

  • 实现简略的权限管制
  • 实现简略的日志

权限管制

pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PermissionAnnotation{}

aspect

@Aspect
@Component
@Order(1)
public class PermissionFirstAdvice {@Pointcut("@annotation(xx.xx.xx.PermissionAnnotation)")
    private void permissionCheck() {}

    @Around("permissionCheck()")
    public Object permissionCheckFirst(ProceedingJoinPoint joinPoint) throws Throwable {System.out.println(System.currentTimeMillis());

        // 获取申请参数
        Object[] objects = joinPoint.getArgs();
        String userName = (String) objects[0];

        if (!userName.equals("admin")) {return "失败";}
        return joinPoint.proceed();}
}

controller

@RestController
@RequestMapping(value = "/permission")
public class TestController {@RequestMapping(value = "/check", method = RequestMethod.POST)
    @PermissionsAnnotation()
    public String getGroupList(@RequestParam String userName) {return "Hello"+userName;}
}

日志

pom

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
    </dependencies>

aspect

@Aspect
@Component
public class OperLogAspect {

    // 操作切入点
    @Pointcut("@annotation(com.bothsavage.annotation.OperLog)")
    public void operLogPoinCut() {}


    // 失常返回告诉
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        OperationLog operlog = new OperationLog();
        try {MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            OperLog opLog = method.getAnnotation(OperLog.class);
            methodName = className + "." + methodName;
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            String params = JSON.toJSONString(rtnMap);

            operlog.setOperId(IdUtil.randomUUID());
            operlog.setOperModul(opLog.operModul());
            operlog.setOperType(opLog.operType());
            operlog.setOperDesc(opLog.operDesc());
            operlog.setOperMethod(methodName); // 申请办法
            operlog.setOperRequParam(params); // 申请参数
            operlog.setOperRespParam(JSON.toJSONString(keys)); // 返回后果
            operlog.setOperUri(request.getRequestURI()); // 申请 URI
            operlog.setOperCreateTime(new Date()); // 创立工夫

            // 打印日志
            System.out.println(JSON.toJSONString(operlog));
        } catch (Exception e) {e.printStackTrace();
        }
    }
    
        // 转换 request 申请参数
    public Map<String, String> converMap(Map<String, String[]> paramMap) {Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    // 转换异样信息为字符串
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}

实体类

package com.bothsavage.entity;

import lombok.Data;

import java.util.Date;

@Data
public class OperationLog {
    private String operId;
    private String operModul;
    private String operType;
    private String operDesc;
    private String OperMethod;
    private String OperRequParam;
    private String OperRespParam;
    private String OperUserId;
    private String OperUserName;
    private String OperIp;
    private String OperUri;
    private Date OperCreateTime;
    private String OperVer;
}

annotation

@Target(ElementType.METHOD) // 注解搁置的指标地位,METHOD 是可注解在办法级别上
@Retention(RetentionPolicy.RUNTIME) // 注解在哪个阶段执行
@Documented
public @interface OperLog {String operModul() default ""; // 操作模块
    String operType() default "";  // 操作类型
    String operDesc() default "";  // 操作阐明}

controller

@RestController
public class TestController {@GetMapping("/test/{testName}")
    @OperLog(operModul = "测试模块",operType = "test",operDesc = "这个是用来测试的")
    public String test(@PathVariable String testName){return  "hello"+testName;}
}

参考

[1]. 把本人牛逼到了,在 SpringBoot 用 AOP 切面实现一个权限校验 …

[2].Spring AOP 实现性能权限校验性能

[3].SpringAop 实现权限校验与日志打印

[4]. 基于 Spring AOP 实现的权限管制

[5]. 应用 SpringBoot AOP 记录操作日志、异样日志

本文作者: Both Savage

本文链接: https://bothsavage.github.io/…

版权申明: 本博客所有文章除特地申明外,均采纳 BY-NC-SA 许可协定。转载请注明出处!

正文完
 0