spring aop快速实现日志记录请求的参数及结果

本文介绍了如何在SpringMVC项目中使用AOP(面向切面编程)实现对Controller方法的请求参数和返回结果的日志记录,展示了`@RestController`,`@RequestMapping`,和`@Autowired`等Spring框架特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单写个请求

package com.example.springdemo.controller;

import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RequestMapping("/A")
@RestController
public class AbcController {
    @PostMapping("/a")
    public Map<String, String> a(@RequestBody(required = false) Map<String, String> q) {
        q.put("a", "aaa");
        return q;
    }

    @GetMapping("/B")
    public String b() {
        return "bbb";
    }

    @GetMapping("/C/{id}")
    public String c(@PathVariable String id) {
        return "ccc" + id;
    }
}

aop然后拿请求的参数及结果

package com.example.springdemo.aop;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.http.HttpRequest;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpSession httpSession;
    @Autowired
    private HttpServletRequest request;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("execution(* com.example.springdemo.controller.*.*(..))")
    public void operLogPoinCut() {
    }

    @Before("operLogPoinCut()")
    public void before(JoinPoint joinPoint) {
        System.out.println("before" + joinPoint.toString());

        //请求参数
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            System.out.println("args" + joinPoint.getArgs()[0]);
        }

        System.out.println("ip" + request.getRemoteAddr());
        System.out.println("url" + request.getRequestURI());
    }

    @AfterReturning(value = "operLogPoinCut()", returning = "res")
    public void after(Object res) {
        //返回结果
        System.out.println("after" + res.toString());
    }


    @AfterThrowing(value = "operLogPoinCut()", throwing = "exception")
    public void after(JoinPoint joinPoint, Exception exception) {
        //返回结果
        System.out.println("afterThrowing" + exception.getMessage());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值