springboot 中配置自定义拦截器

主要分成两步走即可

1、实现拦截器接口

2、配置类添加自定义的拦截器

第一步:实现拦截器接口,代码如下

@Component // 注解必要有,声明组件  放入到容器当中
public class AuthIntercept implements HandlerInterceptor { 
 // 实现 spring的拦截器接口 HandlerInterceptor
    
   // 模仿登录  
   @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
            if (request.getSession().getAttribute("loginfo")!=null){// 已经登陆成功
                return true;  //则允许继续执行
            }else {
                System.out.println("跳转到登陆页面");
               // request.getRequestDispatcher("/user/login").forward(request,response);
                response.sendRedirect("/user/login");// 拦截后跳转到其他页面
                return false;// 不继续执行
            }
    }
}

 

第二步:配置类中增加自定义的拦截器

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    AuthIntercept authIntercept;
@Override
public void addInterceptors(InterceptorRegistry registry) {
    // addPathPatterns("/**") 表示拦截所有的请求,
    // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
    InterceptorRegistration loginRegistry = registry.addInterceptor(authIntercept)
            .addPathPatterns("/**")
            .excludePathPatterns("/user/login", "/user/register");

   // 几种写法均可

    // 拦截路径
    // 排除路径
    loginRegistry.excludePathPatterns("/");
    loginRegistry.excludePathPatterns("/error");
    loginRegistry.excludePathPatterns("/login");
    loginRegistry.excludePathPatterns("/loginout");
    loginRegistry.excludePathPatterns("/WEB-INF/jsp/**/*.jsp");

    // 排除资源请求
    loginRegistry.excludePathPatterns("/static/**/*.css");
    loginRegistry.excludePathPatterns("/static/**/*.js");
    loginRegistry.excludePathPatterns("/static/**/*.*");
    loginRegistry.excludePathPatterns("/static/**/*.png");

}

}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值