SpringBoot(五):SpringBoot使用拦截器

1.按照SpringMVC的方式编写一个拦截器:

2.配置一个类   implements WebMvcConfigurer 接口 为该类添加注解@Configuration  (等价于一个spring的xml文件 比如applicationContext.xml) 标注一个配置类,让Springboot扫描到。覆盖其中的方法并添加已经编写好的拦截器

贴段代码:

@Configuration   // 等价于一个spring的xml文件 比如applicationContext.xml
public class WebConfig implements WebMvcConfigurer {
    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截器要拦截的路径
        String [] pathPatterns = {
                "/**"
        };
        // 拦截器不拦截的路径
        String [] excluedPathPatterns = {
                "/boot/hello",
                "boot/jsp"
        };
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns(pathPatterns).excludePathPatterns(excluedPathPatterns);

        //如果项目中有多个拦截器,把上面代码在复制一行,修改参数即可

    }
}

  

addPathPatterns(pathPatterns)和excludePathPatterns(excluedPathPatterns)是可变参数,二u过要拦截的路径只有一条,可以直接写路径名字,不用写数组,如
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/boot/**").excludePathPatterns(/boot/login);

  

转载于:https://www.cnblogs.com/shenlailai/p/10464197.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值