欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

(入门SpringBoot)SpringBoot加接口操作日志好方法(九)

程序员文章站 2022-03-07 10:10:11
用Spring的切面去做,慕课网上的大神的小妙招,被我拷贝下来了。import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Compon... ......
用spring的切面去做,慕课网上的大神的小妙招,被我拷贝下来了。
import org.aspectj.lang.joinpoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.component; import org.springframework.util.stringutils; import org.springframework.web.context.request.requestcontextholder; import org.springframework.web.context.request.servletrequestattributes; import javax.servlet.http.httpservletrequest; /** * 作用实现拦截http请求. */ @aspect @component //把这个文件引入到spring容器里面去. public class httpaspect { @pointcut("execution(public * com.account.demo.controller.*.*(..))") public void log(){ } /** * 拦截那些方法.请求前. * joinpoint 获取类方法和类名对象. */ @before("log()") public void logbefore(joinpoint joinpoint){ system.out.println("拦截了getinfo方法"); //url,method,ip,类方法,参数. //springboot通过requestcontextholder获取httprequest和httpresponse servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes(); //javax.servlet.http.httpservletrequest httpservletrequest request = attributes.getrequest(); system.out.println("url"+request.getrequesturl()); system.out.println("method"+request.getmethod()); system.out.println("ip"+request.getremoteaddr()); //类方法. system.out.println("类方法"+joinpoint.getsignature().getdeclaringtypename() +"."+ joinpoint.getsignature().getname() ); //参数: system.out.println("类方法"+joinpoint.getargs()); } /** * 拦截那些方法.请求后. */ @after("log()") public void logafter(){ system.out.println("拦截了getinfo方法.之后"); } /** * 返回参数. * @param object 入参 */ @afterreturning(returning = "object",pointcut = "log()") public void doafterreturning(object object){ system.out.println(object); } }