最近项目用到springboot,就是需要配置一些东西.比如用aop处理请求.方法前通知获取url,method,ip,类方法,参数,方法后通知,返回参数,而且还可以记录一下日志.下面是操作的代码.
package com.imooc.shoptest001.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * 刘运通 * 20190324 * 作用实现拦截http请求. */ @Aspect @Component //把这个文件引入到Spring容器里面去. public class HttpAspect { @Pointcut("execution(public * com.imooc.shoptest001.controller.UserController.*(..))") 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); } }