springboot设置拦截器的方法

springboot设置拦截器的方式:
1、编写一个类,在类上面加上@Configuration注解,然后继承 WebMvcConfigurerAdapter。
重写父类的方法:addInterceptors,然后在方法里面在在写一个拦截器的类方法。
@Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor  = new HandlerInterceptor() {

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {
                System.out.println("开始执行........");
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                    ModelAndView modelAndView) throws Exception {
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                    Exception ex) throws Exception {
                
            }
        };
            registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
2、编写一个方法实现HandlerInterceptor接口。
public class MyInterceptors2 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("运行时执行。。。。。。。。。。。。。");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        
    }
}
 开启拦截器的配置路径,在写一个类,这个类要加上@Configuration,继承WebMvcConfigurerAdapter父类,重写addInterceptors方法。
 @Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //对所有的进行拦截   放行登录页面和首页
        registry.addInterceptor(new MyInterceptors2()).addPathPatterns("/**").excludePathPatterns("/user/login","index.html");
    }

    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值