美文网首页
RESTful API的拦截

RESTful API的拦截

作者: Burning_6c93 | 来源:发表于2019-02-04 20:14 被阅读0次
  • 过滤器(Filter)

依赖于servlet容器。在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个过滤器实例只能在容器初始化时调用一次。使用过滤器的目的是用来做一些过滤操作,获取我们想要获取的数据,比如:在过滤器中修改字符编码;在过滤器中修改HttpServletRequest的一些参数,包括:过滤低俗文字、危险字符等


@Slf4j
//@Component
public class TimeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("time filter init");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("filter start");
        long startTime = new Date().getTime();
        filterChain.doFilter(servletRequest, servletResponse);
        log.info("consumingTime:{}",new Date().getTime()-startTime);
        log.info("filter end");
    }
    @Override
    public void destroy() {
        log.info("time filter destroy");
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer{
    @Bean
    public FilterRegistrationBean timeFilter() {
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new TimeFilter());
        ArrayList<String> urls = new ArrayList<>();
        urls.add("/*");
        registrationBean.setUrlPatterns(urls);
        return registrationBean;
    }
}
  • 过滤器生命周期
    • Filter的创建和销毁由web服务器负责。 web应用程序启动时,web服务器将创建Filter的实例对象,并调用其init方法,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作,filter对象只会创建一次,init方法也只会执行一次。通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。
    • web容器调用destroy方法销毁Filter。destroy方法在Filter的生命周期中仅执行一次。在destroy方法中,可以释放过滤器使用的资源。

  • 拦截器(Interceptor)

拦截器是AOP实现的一种策略,在AOP中用于在访问某个方法或字段之前,进行拦截,在执行之前或之后加入某些处理。
SpringMVC 中的Interceptor 拦截请求是通过HandlerInterceptor 来实现的。在SpringMVC 中定义一个Interceptor 非常简单,主要有两种方式,第一种方式是要定义的Interceptor类要实现了Spring 的HandlerInterceptor 接口,或者是这个类继承实现了HandlerInterceptor 接口的类,比如Spring 已经提供的实现了HandlerInterceptor 接口的抽象类HandlerInterceptorAdapter ;第二种方式是实现Spring的WebRequestInterceptor接口,或者是继承实现了WebRequestInterceptor的类。


@Slf4j
@Component
public class TimeInterceptor implements HandlerInterceptor {
  //在handler执行之前,返回 boolean 值,true 表示继续执行,false 为停止执行并返回
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle");
        //拦截器可以拿到请求转向的具体类和方法
        log.info(((HandlerMethod) handler).getBean().getClass().getName());
        log.info(((HandlerMethod) handler).getMethod().getName());
        request.setAttribute("startTime", new Date().getTime());
        return true;
    }
    //在handler执行之后, 可以在返回之前对返回的结果进行修改 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle consumingTime:{}", new Date().getTime() - (long) request.getAttribute("startTime"));
    }
  //进行资源清理工作
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion consumingTime:{},ex:{}", new Date().getTime() - (long) request.getAttribute("startTime"), ex);

    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer{
    @Autowired
    private TimeInterceptor timeInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }
}
  • 两者比较
    1. filter基于函数回调,interceptor基于java反射机制;
    2. filter依赖于servlet容器; 拦截器是一个Spring的组件,归Spring管理,配置 在Spring文件中,因此能使用Spring里的任何资源、对象,例如 Service对象、数据源、事务管理等,通过IoC注入到拦截器即可。
    3. filter对所有的请求进行过滤,interceptor只对action请求起作用。
    4. 在action的生命周期里,Interceptor可以被多次调用,而Filter只能在容器初始化时调用一次。
    5. 执行顺序:过滤前-拦截前-action执行-拦截后-过滤后

  • 切片(Aspect)


    image.png
@Aspect
@Component
@Slf4j
public class TimeAspect {
    @Around("execution(* com.dzg.web.controller.UserController.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("timeAspect start");
        Object proceed = joinPoint.proceed();
        //Aspect可以拿到请求中的携带的参数信息,这是拦截器无法做到的,但其无法拿到request和response
        Object[] args = joinPoint.getArgs();
        for(Object arg :args){
            log.info("arg:{}",arg);
        }
        log.info("timeAspect end");
        return proceed;

    }
}
  • 拦截顺序
    image.png

相关文章

  • restful api 拦截

    1、过滤器(Filter)(1)自定义 (2)第三方 2、拦截器(Interceptor) (1)定义拦截器 (2...

  • RESTful API的拦截

    RESTful API的拦截 场景:对RESTfulAPI作统一的处理,比如希望对所有的RESTfulAPI记录服...

  • RESTful API的拦截

    过滤器(Filter) 依赖于servlet容器。在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个...

  • 过滤器(filter)/拦截器(Interceptor)/切片(

    Restful API 的拦截 在某些情况下,会有需求对api拦截做一些统一的业务处理。简单的如api执行时间等。...

  • Flutter 常用第三方库整理

    网络请求 Dio dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器...

  • Flutter笔记(七):Dio网络请求、Json数据解析以及泛

    前言 dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、...

  • Flutter常用插件

    Dio Dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消...

  • Flutter-dio网络请求封装

    dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Coo...

  • Dio的封装

    dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Coo...

  • Flutter 常用框架

    Dio2 Dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取...

网友评论

      本文标题:RESTful API的拦截

      本文链接:https://www.haomeiwen.com/subject/vduxsqtx.html