SpringBoot添加拦截器

本文介绍如何使用Spring MVC框架配置拦截器,通过添加注解和重写addInterceptors方法实现请求拦截,并提供了测试拦截器的方法。

【配置步骤】
1.为拦截方法类添加注解@Configuration
2.继承WebMvcConfigurerAdapter类
3.重写addInterceptors方法,添加需要拦截的请求

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter{  
    @Override
    public void addInterceptors(InterceptorRegistry registry) {     
        //表示拦截所有的请求
        registry.addInterceptor(new InterceptorTest()).addPathPatterns("/*/**");
        super.addInterceptors(registry);
    }
}
public class InterceptorTest implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {     
        System.out.println("拦截成功");
        return false;
    }
        //HandlerInterceptor仍有其它方法,已省略
}

【测试拦截器】
1.配置mapping方法

    @RequestMapping("/interceptor")
    @ResponseBody
    String interceptorTest() {
        return "拦截器未开启";
    }

2.不开启拦截器,即把InterceptorTest.preHandle改为return true
1273068-20180407202039539-206085689.gif

3.开启拦截器,即把InterceptorTest.preHandle改为return false
1273068-20180506204017269-601146974.gif

转载于:https://www.cnblogs.com/likailun/p/9323578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值