*IT SpringAOP:足跡第十八步瞭解SpringAOP(實現許可權認證、日誌)

原玉輝發表於2018-03-11

 

方案1:

1.1)準備切面,實現許可權認證、日誌


@Aspect
@Component
public class LogAspect {

    Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Value("${spring.application.name}")
    private String serverName;
    @Pointcut("@annotation(com.xxx.annotation.LogAnnotation)")
    public void beforePointCut () {}

    @Before("beforePointCut()")
    public void before (JoinPoint joinPoint) {
        if (joinPoint == null) {
            return;
        }
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] methodArgs = joinPoint.getArgs();
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        String logType = logAnnotation.type();
        String logValue = logAnnotation.value();
        String userName = SecurityUtils.getCurrentUserLogin();
        if (StringUtils.isEmpty(userName)) {
            userName = "使用者未登入";
        }
        String ip = getIpAddress(request);
        StringBuilder args = new StringBuilder();
        for (Object o : methodArgs) {
            args.append(o);
            args.append("&");
        }
        if (args.length() > 0) {
            args = args.delete(args.length()-1,args.length());
        }

        logger.info(userName+"|"+className+"|"+methodName+"|"+ip+"|"+logType+"|"+args.toString()+"|"+serverName+"|"+logValue);
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

 

1.2)生成切點註解

package com.xxx.annotation;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
    String value() default "";
    String type() default "";
}

1.3)在介面Action下add方法處呼叫切面


@RestController
@RequestMapping("/api")
public class AdminLogController {
    @Autowired
    private AdminLogService adminLogService;
    @LogAnnotation(type = Constants.LOG_TYPE_ADD,value = "admin的add日誌")
    @PostMapping(value = "/setAdminLog")
    @ApiOperation(value="admin的add日誌", notes="新增資料")
    public ResponseEntity<ResultStatus> addUserLog(@RequestBody AdminLogEntity adminLogEntity){
        ResultStatus resultStatus = adminLogService.save(adminLogEntity);
        return new ResponseEntity<ResultStatus>(resultStatus, HttpStatus.OK);
    }
}

方案2:

2.1)準備切面(@Aspect)與切點@Pointcut(介面Action);

 

2.2)在介面Action下add方法處呼叫切面(AOP核心是攔截);

3)DTO

3.1)Result

3.2)介面中調取統一結果集Result

3.3)json規範

相關文章