springboot 拦截器 Interceptor

2017-11-16

38

0

技术:springboot + Interceptor

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:springboot 拦截器支持

新建springboot项目

详见pom文件

新建拦截器

public class TestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("hi, this is from TestInterceptor");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

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

    }
}

注册拦截器

//spreingboot 会自动扫描到这个类,并且注册拦截器
@Configuration
public class AppConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

preHandle()方法添加断点

访问 http://localhost:8080/greeting, 发现命中断点,拦截器生效

 

ps:

1. preHandle方法中最后一个输入参数, 类型会变化, 可以猜猜看

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think