SpringBoot拦截器的使用

一、首先建立拦截器,继承HandlerInterceptor

public class CustomInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        MsgUtils.println("自定义拦截器->执行之前");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        MsgUtils.println("自定义拦截器->执行之后");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}

或者继承HandlerInterceptorAdapter,选择实现其中的方法

public class MyInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MsgUtils.println("自定义拦截器-适配器模式->执行之前");
        return true;
    }
}

二、设置添加拦截器

@Configuration
public class WebmvcConfig extends WebMvcConfigurerAdapter {
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/**");
    }

}

好了,测试一下:


成功执行。多个拦截器的执行顺序跟添加顺序一致。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xxkalychen/article/details/78003754
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭