Spring Boot (5) 拦截器

Spring Boot (5) 拦截器

Scroll Down

Spring MVC 提供了AOP风格的拦截器, 拥有更加精细的拦截处理能力.

注册拦截器

  1. 创建项目
  2. 创建拦截器实现HandlerInterceptor接口
/**
 * 拦截器示列
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/25
 * @Description: com.iscolt.interceptor.web
 * @version: 1.0
 */
public class MyInterceptor implements HandlerInterceptor {

    /**
     * 此方法返回true才会执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle : 抱歉, 我第一个执行");
        return true;
    }

    /**
     * 拦截链内, 所有拦截器返回成功时才被调用
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle : 你们都是好人, 我才执行给你们看");
    }

    /**
     * preHandle 返回false 后, 后面的都不执行
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion : 只有preHandle大人发话, 我才放行");
    }
}

执行顺序 : preHandle >> Controller >> postHandle >> afterCompletion

  1. 配置拦截器
/**
 * 配置拦截器
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/25
 * @Description: com.iscolt.interceptor.config
 * @version: 1.0
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * addPathPatterns 表示拦截路径
     * excludePatterns 表示排除路径
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/hello");
    }
}
支付宝 微信