restful api 拦截

1、过滤器(Filter)
(1)自定义

@Component  //所有的url都会作用到
public class TimeFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("time filter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //计算执行时间
        System.out.println("time filter start");
        long start = new Date().getTime();
        //执行servlet
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("time filter 耗时:" + (new Date().getTime() - start));
        System.out.println("time filter end");

    }

    @Override
    public void destroy() {
        System.out.println("time filter destory");
    }
}

(2)第三方


//假设这是第三方提供的过滤器,没有使用@Component,则要通过@Configuration配置
public class TimeFilter2 implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("time filter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //计算执行时间
        System.out.println("time filter start");
        long start = new Date().getTime();
        //执行servlet
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("time filter 耗时:" + (new Date().getTime() - start));
        System.out.println("time filter end");

    }

    @Override
    public void destroy() {
        System.out.println("time filter destory");
    }
}

@Configuration
public class WebConfig {

    @Bean
    public FilterRegistrationBean timeFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        TimeFilter2 timeFilter2 = new TimeFilter2();
        registrationBean.setFilter(timeFilter2);

        //指定作用url
        List urls = new ArrayList<>();
        urls.add("/*");
        registrationBean.setUrlPatterns(urls);
        return registrationBean;
    }

}

2、拦截器(Interceptor)

(1)定义拦截器

@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {

        httpServletRequest.setAttribute("startTime", new Date().getTime());
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        System.out.println(handlerMethod.getBean().getClass().getName());
        System.out.println(handlerMethod.getMethod().getName());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
        Long start = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("time interceptor 耗时:" + (new Date().getTime() - start));
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
        //无论控制器执行失败与否都会执行到这一步
        Long start = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("time interceptor 耗时:" + (new Date().getTime() - start));

    }
}

(2)configuration管理

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private TimeInterceptor timeInterceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timeInterceptor);
    }
}

备注:@ControllerAdvice控制器异常处理是在拦截器afterCompletion方法之前执行的。所以一般控制器异常被处理了,就不会把异常抛到拦截器,除非异常没有被定义的控制器异常处理捕获到。

@ControllerAdvice
public class ControllerExceptionHandler {

    //用于捕获抛出的请求自定义异常,捕获后对异常加工并把加工后的值返回
    @ExceptionHandler(UserNotExistException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map handlerUserNotExistException(UserNotExistException ex) {
        return new Hashtable() {{
            put("id", ex.getId());
            put("message", ex.getMessage());
        }};
    }

}

3、切片(Aspect)
3.1满足AOP类需要具备的条件
(1)切入点(注解)
在哪些方法上起作用;在什么时候起作用
(2)增强(方法)
起作用时执行的业务逻辑

        
            org.springframework.boot
            spring-boot-starter-aop
        
@Aspect
@Component
public class TimeAspect {

    @Around("execution(* com.imooc.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);
        }

        Long start = new Date().getTime();
        //pjp.proceed();拿到的返回值是控制器执行完毕返回的值
        Object object = pjp.proceed();
        Long end = new Date().getTime();
        System.out.println("耗时:" + (end - start));
        return object;
    }
}

你可能感兴趣的:(restful api 拦截)