使用aop注解打印请求(拦截所有和拦截指定方法)

1.使用springAOP切面拦截所有controller请求

1.添加pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

2.添加aspect包下的LogAspect文件

package com.futureport.wiki.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;

import com.futureport.wiki.utils.RequestContext;
import com.futureport.wiki.utils.SnowFlake;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LogAspect {

    @Resource
    SnowFlake snowFlake;
    private final static Logger LOG = LoggerFactory.getLogger(LogAspect.class);

    /** 定义一个切点 */
    @Pointcut("execution(public * com.futureport.*.controller..*Controller.*(..))")
    public void controllerPointcut() {}


    @Before("controllerPointcut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        // 增加日志流水号
        MDC.put("LOG_ID", String.valueOf(snowFlake.nextId()));

        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        String name = signature.getName();

        // 打印请求信息
        LOG.info("------------- 开始 -------------");
        LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
        LOG.info("类名方法: {}.{}", signature.getDeclaringTypeName(), name);
        LOG.info("远程地址: {}", request.getRemoteAddr());

        RequestContext.setRemoteAddr(getRemoteIp(request));

        // 打印请求参数
        Object[] args = joinPoint.getArgs();
      // LOG.info("请求参数: {}", JSONObject.toJSONString(args));

      Object[] arguments  = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest
                    || args[i] instanceof ServletResponse
                    || args[i] instanceof MultipartFile) {
                continue;
            }
            arguments[i] = args[i];
        }

        // 排除字段,敏感字段或太长的字段不显示
        String[] excludeProperties = {"password", "file"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
        excludefilter.addExcludes(excludeProperties);
        LOG.info("请求参数: {}", JSONObject.toJSONString(arguments, excludefilter));
    }

    @Around("controllerPointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 排除字段,敏感字段或太长的字段不显示
        String[] excludeProperties = {"password", "file"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
        excludefilter.addExcludes(excludeProperties);
        LOG.info("返回结果: {}", JSONObject.toJSONString(result, excludefilter));
        LOG.info("------------- 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime);
        return result;
    }

    /**
     * 使用nginx做反向代理,需要用该方法才能取到真实的远程IP
     * @param request
     * @return
     */
    public String getRemoteIp(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.getRemoteAddr();
        }
        return ip;
    }

}

2.加到方法上拦截指定的controller或者service

1.添加pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

2.添加annotation包下的ControllerLog和ServiceLog文件

ControllerLog

package com.futureport.wiki.annotation;
import java.lang.annotation.*;

/**
 * ClassName: ControllerLog
 * Description: 自定义注解 拦截Controller
 * date: 2021/9/7 1:37 PM
 *
 * @author zhihao.huang
 *         Copyright (c) 2019. convertlab.com All Rights Reserved.
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ControllerLog {
    String description()  default "";
}

ServiceLog

package com.futureport.wiki.annotation;

import java.lang.annotation.*;

/**
 * ClassName: ServiceLog
 * Description: 自定义注解 拦截service
 * date: 2021/9/7 1:37 PM
 *
 * @author zhihao.huang
 *         Copyright (c) 2019. convertlab.com All Rights Reserved.
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ServiceLog {
    String description()  default "";
}

3.添加aspect包下的SystemLogAspect文件

package com.futureport.wiki.aspect;

import com.alibaba.fastjson.JSONObject;
import com.futureport.wiki.annotation.ControllerLog;
import com.futureport.wiki.annotation.ServiceLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * ClassName: SystemLogAspect
 * Description: 通用日志切点类
 * date: 2021/9/7 1:37 PM
 *
 * @author zhihao.huang
 *         Copyright (c) 2019. convertlab.com All Rights Reserved.
 */
@Aspect
@Component
public class SystemLogAspect {
    private final static Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    //Service层切点
    @Pointcut("@annotation(com.futureport.wiki.annotation.ServiceLog)")
    public  void serviceAspect() {
    }

    //Controller层切点
    @Pointcut("@annotation(com.futureport.wiki.annotation.ControllerLog)")
    public  void controllerAspect() {
    }

    public SystemLogAspect(){
        logger.info("@@@ start SystemLogAspect ");
    }

    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint 切点
     */
    @Before("controllerAspect()")
    public  void doBefore4control(JoinPoint joinPoint) {
        try {
            Logger log = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
            log.info(">>> Execute Controller: {}.{}()", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName());
        }  catch (Exception e) {
            e.printStackTrace();
            if(joinPoint != null && joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null){
                LoggerFactory.getLogger(joinPoint.getTarget().getClass()).error("Exception in doBefore4control: {}", e.getMessage());
            }else{
                logger.error("Exception in doBefore4control: {}", e.getMessage());
            }
        }
    }

    @Before("serviceAspect()")
    public  void doBefore4service(JoinPoint joinPoint) {
        try {
            String params = "";
            if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {
                for ( int i = 0; i < joinPoint.getArgs().length; i++) {
                    try {
                        params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
                    }catch (Exception e){}
                }
            }
            Logger log = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
            log.info(">>> Execute Service:  {}.{}({})", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName(), params);
        }  catch (Exception ex) {
            ex.printStackTrace();
            if(joinPoint != null && joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null){
                LoggerFactory.getLogger(joinPoint.getTarget().getClass()).error("Exception in doBefore4service: {}", ex.getMessage());
            }else{
                logger.error("Exception in doBefore4control: {}", ex.getMessage());
            }
        }
    }

    @AfterReturning(pointcut="serviceAspect()", returning="returnValue")
    public  void after4service(JoinPoint joinPoint, Object returnValue) {
        try {
            Logger log = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
            String response = "";
            try{
                response = JSONObject.toJSON(returnValue).toString();
            }catch (Exception e){
            }

            log.info("<<<< Service : {}.{}() Response. {}", joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName(), response);
        }  catch (Exception ex) {
            ex.printStackTrace();
            if(joinPoint != null && joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null){
                LoggerFactory.getLogger(joinPoint.getTarget().getClass()).error("Exception in after4service: {}", ex.getMessage());
            }else{
                logger.error("Exception in doBefore4control: {}", ex.getMessage());
            }
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于service层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public  static String getServiceMethodDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(ServiceLog.class).description();
                    break;
                }
            }
        }
        return description;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public  static String getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(ControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }

}

4.在controller和service文件中使用自定义注解

@ControllerLog
@RequestMapping("/ebook/list")
public CommonResp ebook(EbookReq req) {
    CommonResp<List<EbookResp>> resp = new CommonResp<>();
  
@ServiceLog
public List<EbookResp> list(EbookReq req) {
    EbookExample ebookExample = new EbookExample();
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java中,可以使用注解AOP(面向切面编程)技术来拦截Controller的所有方法。 首先,需要创建一个自定义的注解,用于标识需要拦截方法。可以使用如下的注解定义: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Intercept { } ``` 接下来,创建一个切面类,用于实现拦截逻辑。可以使用如下的切面类定义: ```java import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class ControllerInterceptor { @Pointcut("@annotation(Intercept)") public void interceptedMethods() {} @Before("interceptedMethods()") public void beforeIntercept() { // 在方法执行之前拦截的逻辑 } @After("interceptedMethods()") public void afterIntercept() { // 在方法执行之后拦截的逻辑 } } ``` 在上述的切面类中,使用了`@Aspect`注解表示这是一个切面类,使用了`@Component`注解将切面类交由Spring管理。`@Pointcut`注解定义了需要拦截方法,此处使用了`@annotation(Intercept)`表示拦截带有`Intercept`注解方法。`@Before`和`@After`注解分别表示在方法执行前和执行后进行拦截处理。 最后,在需要拦截Controller方法使用`@Intercept`注解进行标记,例如: ```java @RestController public class MyController { @Intercept @GetMapping("/") public String index() { return "Hello World"; } } ``` 这样,只要在Controller方法使用了`@Intercept`注解,就会触发切面类中的拦截逻辑。 需要注意的是,上述代码使用Spring AOP来实现AOP功能,因此需要在Spring配置文件中开启AOP的支持。另外,还需要引入相关的依赖,例如Spring AOP的依赖。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值