在springboot中使用rest服务时,往往需要对controller层的请求进行拦截或者获取请求数据和返回数据,就需要过滤器、拦截器或者切片。

过滤器(Filter):对HttpServletRequest处理,也可以对HttpServletResponse 进行后处理,无法获取请求方法的信息。

拦截器(Interceptor):可以获取HttpServletRequest、HttpServletResponse的数据,也可以获取请求方法的信息,但是无法获取请求的参数和返回参数。

切片(Aspect):aop的切片可以获取请求的参数和返回的值,但是无法获取HttpServletRequest、HttpServletResponse的数据。

    1. 过滤器(Filter):

      @Component
      public class TimeFilter implements Filter {
        //销毁时
      @Override
      public void destroy() {
      System.out.println("time filter destroy");
      }
        //逻辑代码
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
      System.out.println("time filter start");
      long start = new Date().getTime();
      chain.doFilter(request, response);
      System.out.println("time filter 耗时:"+ (new Date().getTime() - start));
      System.out.println("time filter finish");
      }
        //加载前
      @Override
      public void init(FilterConfig arg0) throws ServletException {
      System.out.println("time filter init");
      } }

      这样所有请求都能获取,如果过滤器没法加@Component定义为组件引用,可以在配置文件中引用

      @Configuration
      public class WebConfig extends WebMvcConfigurerAdapter { @Bean
      public FilterRegistrationBean timeFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); TimeFilter timeFilter = new TimeFilter();
      registrationBean.setFilter(timeFilter); List<String> urls = new ArrayList<>();
      urls.add("/*");//获取所有请求
      registrationBean.setUrlPatterns(urls); return registrationBean; } }
    2. 拦截器(Interceptor)
      @Component
      public class TimeInterceptor implements HandlerInterceptor {
        // 在业务处理器处理请求之前被调用
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
      System.out.println("preHandle"); System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
      System.out.println(((HandlerMethod)handler).getMethod().getName()); request.setAttribute("startTime", new Date().getTime());
      return true;
      }
      // 在业务处理器处理请求完成之后,生成视图之前执行
      @Override
      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
      System.out.println("postHandle");
      Long start = (Long) request.getAttribute("startTime");
      System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start)); }
        //请求完成之后
      @Override
      public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
      System.out.println("afterCompletion");
      Long start = (Long) request.getAttribute("startTime");
      System.out.println("time interceptor 耗时:"+ (new Date().getTime() - start));
      System.out.println("ex is "+ex); } }

      创建组件后需要在配置文件中定义下

      @Configuration
      public class WebConfig extends WebMvcConfigurerAdapter { @SuppressWarnings("unused")
      @Autowired
      private TimeInterceptor timeInterceptor; @Override
      public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(timeInterceptor);
      } }
    3. 切片(Aspect)
      @Aspect
      @Component
      public class TimeAspect { @Around("execution(* com.project.web.controller.UserController.*(..))")
      public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable { System.out.println("time aspect start"); Object[] args = pjp.getArgs();
      for (Object arg : args) {
      System.out.println("arg is "+arg);//获取请求参数
      } long start = new Date().getTime(); Object object = pjp.proceed();//获取返回值 System.out.println("time aspect 耗时:"+ (new Date().getTime() - start)); System.out.println("time aspect end"); return object;
      } }

一个请求的处理顺序是过滤器(Filter)->拦截器(Interceptor)->切片(Aspect)

springboot中使用Filter、Interceptor和aop拦截REST服务的更多相关文章

  1. SpringBoot中使用LoadTimeWeaving技术实现AOP功能

    目录 1. 关于LoadTimeWeaving 1.1 LTW与不同的切面织入时机 1.2 JDK实现LTW的原理 1.3 如何在Spring中实现LTW 2. Springboot中使用LTW实现A ...

  2. SpringBoot系列:三、SpringBoot中使用Filter

    在springboot中要使用Filter首先要实现Filter接口,添加@WebFilter注解 然后重写三个方法,下图示例是在Filter中过滤上一届中拿配置的接口,如果是这个接口会自动跳转到/P ...

  3. SpringBoot学习笔记(11)-----SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

    1. activemq 首先引入依赖 pom.xml文件 <dependency> <groupId>org.springframework.boot</groupId& ...

  4. SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

    1. activemq 首先引入依赖 pom.xml文件 <dependency> <groupId>org.springframework.boot</groupId& ...

  5. springboot中使用filter用配置类方式

    在03-springboot-web的Filter包下,创建HeFilter类 代码示例: package com.bjpowernode.springboot.filter; import java ...

  6. springboot中使用filter

    通过注解的方式实现filter过滤器. 创建Filter包,并在该包下创建MyFilter 示例代码: package com.bjpowernode.springboot.filter; impor ...

  7. Spring中过滤器(Filter)和拦截器(Interceptor)的区别和联系

    在我们日常的开发中,我们经常会用到Filter和Interceptor.有时同一个功能.Filter可以做,Interceptor也可以做.有时就需要考虑使用哪一个比较好.这篇文章主要介绍一下,二者的 ...

  8. [AOP拦截 ]SpringBoot+Quartz Aop拦截Job类中的方法

    ​ 最近在工作使用boot+quartz整合,开发定时调度平台,遇到需要对Quartz的Job进行异常后将异常记录到日志表的操作,第一反应就想到了使用Spring的AOP,利用AfterThrowin ...

  9. springboot中使用过滤器、拦截器、监听器

    监听器:listener是servlet规范中定义的一种特殊类.用于监听servletContext.HttpSession和servletRequest等域对象的创建和销毁事件.监听域对象的属性发生 ...

随机推荐

  1. 【服务总线 Azure Service Bus】ServiceBus 队列中死信(DLQ - Dead Letter Queue)问题

    Azure Service Bus 死信队列产生的原因 服务总线中有几个活动会导致从消息引擎本身将消息推送到 DLQ. 如 超过 MaxDeliveryCount 超过 TimeToLive 处理订阅 ...

  2. linux centos8 安装dokcker并启动coreapi

    粘的个人笔记,格式有点乱.勿在意 core api程序包 发布直接部署包: 链接:https://pan.baidu.com/s/1zZe9H1Fevf7DdzfF-MJb9w 提取码:t0ai 源码 ...

  3. 对象部分初始化:原理以及验证代码(双重检查锁与volatile相关)

    对象部分初始化:原理以及验证代码(双重检查锁与volatile相关) 对象部分初始化被称为 Partially initialized objects / Partially constructed ...

  4. ansible-hoc命令行

    ansible一种开源的自动化工具 ansible: hoc命令行: 是一款开源的自动化运维工具 python paramiko #模拟ssh协议批量管理主机 jinja2 #模板语言,主要用来传递变 ...

  5. 从小白到 6 个 offer,我究竟是怎么刷题的?

    最近自习室里又兴起了一阵刷题潮,大家相约刷题~ 今天和大家系统分享下我去年转行时的一个刷题过程和方法,希望对你有所帮助. 首先介绍下我的编程基础,我学的是金融工程专业,硕士时学过 C++ 的课,这也是 ...

  6. [BZOJ 4818/LuoguP3702][SDOI2017] 序列计数 (矩阵加速DP)

    题面: 传送门:https://www.lydsy.com/JudgeOnline/problem.php?id=4818 Solution 看到这道题,我们不妨先考虑一下20分怎么搞 想到暴力,本蒟 ...

  7. js某时间与当前时间差

    function minuteFormat(min){ if(!min){ return '-'; } var result=''; if(min%(60*24*30*12)!=min){ resul ...

  8. MySQL主主数据同步

    环境 操作系统版本:CentOS 6.5 64位MySQL版本:mysql5.6节点1IP:192.168.0.235 主机名:taojiang1-mysql-01节点2IP:192.168.0.23 ...

  9. 理解Task和和async await

    本文将详解C#类当中的Task,以及异步函数async await和Task的关系 一.Task的前世今生 1.Thread 一开始我们需要创建线程的时候一般是通过Thread创建线程,一般常用创建线 ...

  10. 【Kata Daily 190912】Alphabetical Addition(字母相加)

    题目: Your task is to add up letters to one letter. The function will be given a variable amount of ar ...