SpringBoot拦截器


通过实现WebMvcConfigurer并添加@Configuration注解来实现自定义部分SpringMvc配置

定义拦截器


/**
 * 定义一个拦截器
 *
 * @author zrh
 * @date 2022/4/18
 * @apiNote
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle method is running!");
        //  返回true表示放行;返回false表示拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle method is running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion method is running!");
    }
}

定义配置类


/**
 *
 * 定义配置类,注册拦截器
 * @author zrh
 * @date 2022/4/18
 * @apiNote
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    //让Spring注入自定义的拦截类
    @Autowired
    private HandlerInterceptor myInterceptor;

    /**
     * 重写接口中的addInterceptors方法,添加自定义的拦截器类
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //  addPathPatterns表示拦截的资源路径
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

文章作者: zrh
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 zrh !
  目录