在spring boot中,简单几步,使用spring AOP实现一个拦截器:

1、引入依赖:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

2、创建拦截器类(在该类中,定义了拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。):

    1. /**
    2. * 拦截器:记录用户操作日志,检查用户是否登录……
    3. * @author XuJijun
    4. */
    5. @Aspect
    6. @Component
    7. public class ControllerInterceptor {
    8. private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
    9. @Value(“${spring.profiles}”)
    10. private String env;
    11. /**
    12. * 定义拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。
    13. */
    14. @Pointcut(“execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)”)
    15. public void controllerMethodPointcut(){}
    16. /**
    17. * 拦截器具体实现
    18. * @param pjp
    19. * @return JsonResult(被拦截方法的执行结果,或需要登录的错误提示。)
    20. */
    21. @Around(“controllerMethodPointcut()”) //指定拦截器规则;也可以直接把“execution(* com.xjj………)”写进这里
    22. public Object Interceptor(ProceedingJoinPoint pjp){
    23. long beginTime = System.currentTimeMillis();
    24. MethodSignature signature = (MethodSignature) pjp.getSignature();
    25. Method method = signature.getMethod(); //获取被拦截的方法
    26. String methodName = method.getName(); //获取被拦截的方法名
    27. Set<Object> allParams = new LinkedHashSet<>(); //保存所有请求参数,用于输出到日志中
    28. logger.info(”请求开始,方法:{}”, methodName);
    29. Object result = null;
    30. Object[] args = pjp.getArgs();
    31. for(Object arg : args){
    32. //logger.debug(“arg: {}”, arg);
    33. if (arg instanceof Map<?, ?>) {
    34. //提取方法中的MAP参数,用于记录进日志中
    35. @SuppressWarnings(“unchecked”)
    36. Map<String, Object> map = (Map<String, Object>) arg;
    37. allParams.add(map);
    38. }else if(arg instanceof HttpServletRequest){
    39. HttpServletRequest request = (HttpServletRequest) arg;
    40. if(isLoginRequired(method)){
    41. if(!isLogin(request)){
    42. result = new JsonResult(ResultCode.NOT_LOGIN, “该操作需要登录!去登录吗?\n\n(不知道登录账号?请联系老许。)”, null);
    43. }
    44. }
    45. //获取query string 或 posted form data参数
    46. Map<String, String[]> paramMap = request.getParameterMap();
    47. if(paramMap!=null && paramMap.size()>0){
    48. allParams.add(paramMap);
    49. }
    50. }else if(arg instanceof HttpServletResponse){
    51. //do nothing…
    52. }else{
    53. //allParams.add(arg);
    54. }
    55. }
    56. try {
    57. if(result == null){
    58. // 一切正常的情况下,继续执行被拦截的方法
    59. result = pjp.proceed();
    60. }
    61. } catch (Throwable e) {
    62. logger.info(”exception: ”, e);
    63. result = new JsonResult(ResultCode.EXCEPTION, “发生异常:”+e.getMessage());
    64. }
    65. if(result instanceof JsonResult){
    66. long costMs = System.currentTimeMillis() - beginTime;
    67. logger.info(”{}请求结束,耗时:{}ms”, methodName, costMs);
    68. }
    69. return result;
    70. }
    71. /**
    72. * 判断一个方法是否需要登录
    73. * @param method
    74. * @return
    75. */
    76. private boolean isLoginRequired(Method method){
    77. if(!env.equals(“prod”)){ //只有生产环境才需要登录
    78. return false;
    79. }
    80. boolean result = true;
    81. if(method.isAnnotationPresent(Permission.class)){
    82. result = method.getAnnotation(Permission.class).loginReqired();
    83. }
    84. return result;
    85. }
    86. //判断是否已经登录
    87. private boolean isLogin(HttpServletRequest request) {
    88. return true;
    89. /*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken);
    90. if(“1”.equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){
    91. return true;
    92. }else {
    93. return false;
    94. }*/
    95. }
    96. }

转:Spring Boot中使用AOP统一处理Web请求日志的更多相关文章

  1. 46. Spring Boot中使用AOP统一处理Web请求日志

    在之前一系列的文章中都是提供了全部的代码,在之后的文章中就提供核心的代码进行讲解.有什么问题大家可以给我留言或者加我QQ,进行咨询. AOP为Aspect Oriented Programming的缩 ...

  2. Spring Boot中使用AOP统一处理Web请求日志

    AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是Spring框架中的一个重要内容,它通 ...

  3. (转)Spring Boot中使用AOP统一处理Web请求日志

    AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是Spring框架中的一个重要内容,它通 ...

  4. Springboot中使用AOP统一处理Web请求日志

    title: Springboot中使用AOP统一处理Web请求日志 date: 2017-04-26 16:30:48 tags: ['Spring Boot','AOP'] categories: ...

  5. SpringBoot2.0 使用AOP统一处理Web请求日志(完整版)

    一,加入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  6. spring Boot使用AOP统一处理Web请求日志记录

    1.使用spring boot实现一个拦截器 1.引入依赖: <dependency>   <groupId>org.springframework.boot</grou ...

  7. AOP统一处理Web请求日志

    <!--aop--> <dependency> <groupId>org.springframework.boot</groupId> <arti ...

  8. springboot Aop 统一处理Web请求日志

    1.增加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  9. Spring Boot中使用AOP记录请求日志

    这周看别人写的springboot后端代码中有使用AOP记录请求日志,以前没接触过,因此学习下. 一.AOP简介 AOP为Aspect Oriented Programming的缩写,意为:面向切面编 ...

随机推荐

  1. 『题解』洛谷P2170 选学霸

    更好的阅读体验 Portal Portal1: Luogu Description 老师想从\(N\)名学生中选\(M\)人当学霸,但有\(K\)对人实力相当,如果实力相当的人中,一部分被选上,另一部 ...

  2. 由浅入深——从ArrayList浅谈并发容器

    原创作品转载请附:https://www.cnblogs.com/superlsj/p/11655523.html 一.一个案例引发的思考 public class ArrayListTest { p ...

  3. 文件输入输出函数fgetc/fputc及fgets/fputs等文件指针位置的变化

    文件打开后才可以对文件进行操作.也就是说,文件必须经历打开-操作-关闭的过程.如前所述,C语言对文件的操作都是通过调用标准I/O库函数来实现的.文件操作实际是指对文件的读写.文件的读操作就是从文件中读 ...

  4. mpvue+小程序云开发,纯前端实现婚礼邀请函

    请勿使用本文章及源码作为商业用途! 前言 当初做这个小程序是为了婚礼前的需要,结婚之后,希望这个小程序能够留存下来,特地花了一些空闲时间将小程序转化成为“相册类小程序” 体验码 准备工作 mpvue框 ...

  5. docker初解

    1 什么是容器 容器就是在隔离的环境中运行的一个进程,如果进程停止,容器就会退出. 隔离的环境拥有自己的系统文件,ip地址,主机名等 容器是一种软件打包技术 程序:代码,命令进程:正在运行的程序容器的 ...

  6. 三张关联表,大表;单次查询耗时400s,有group by order by 如何优化

    问题SQL: select p.person_id as personId, p.person_name as personName, p.native_place as nativePlace, c ...

  7. 一个简单的C#爬虫程序

    这篇这篇文章主要是展示了一个C#语言如何抓取网站中的图片.实现原理就是基于http请求.C#给我们提供了HttpWebRequest和WebClient两个对象,方便发送请求获取数据,下面看如何实 1 ...

  8. 暑假CV-QKD的相关论文单词集(第一弹)

    CV-QKD  连续变量-量子秘钥分发 Quadrature  正交 Photon     光子 Coherent    连续的,连贯的 Reconciliation   调解 Cryptograph ...

  9. Ubuntu清空回收站

    ubuntu 回收站的具体位置:$HOME/.local/share/Trash/ 执行如下命令清空回收站: sudo rm -fr $HOME/.local/share/Trash/files/ 如 ...

  10. python:Asyncio模块处理“事件循环”中的异步进程和并发执行任务

    python模块Asynico提供了管理事件.携程.任务和线程的功能已经编写并发代码的同步原语. 组成模块: 事件循,Asyncio 每个进程都有一个事件循环. 协程,子例程概念的泛化,可以暂停任务, ...