springboot设置拦截器的方法

本文详细介绍了在 SpringBoot 中配置拦截器的两种方法。第一种是通过创建配置类并继承 WebMvcConfigurerAdapter,重写 addInterceptors 方法来实现全局拦截。第二种是直接实现 HandlerInterceptor 接口,通过配置类注册拦截器。文章提供了具体的代码示例,展示了如何设置拦截规则和排除路径。

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");
    }

    
}

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值