RESTful API的拦截

2019-02-04  本文已影响0人  Burning_6c93

依赖于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;
    }
}

拦截器是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);
    }
}

@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;

    }
}
上一篇下一篇

猜你喜欢

热点阅读