SpringBoot配置拦截器

百度上有很多种方法,我也踩了很多坑.现在我分享一下我自己成功的配置
欢迎大佬多读指教.

先配置一下拦截器配置类

/**
 * 拦截器配置类
 */
package com.example.springbootthmeleaf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class Filter implements WebMvcConfigurer {
    @Autowired
    private Blocker blocker;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	//配置拦截路径
        registry.addInterceptor(blocker).addPathPatterns("/user/**");
    }

}

然后配置创建一个拦截器的实际操作类

package com.example.springbootthmeleaf.config;

import com.example.springbootthmeleaf.util.RedisUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Configuration
public class Blocker implements HandlerInterceptor {
    @Resource
    RedisUtil redisUtil;
    int num =0;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (num!=0){
            //每一个项目对于登陆的实现逻辑都有所区别,我这里使用最简单的Session提取User来验证登陆。
            System.out.println("进入拦截器!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            if (redisUtil.hasKey("user")){
                System.out.println("检测到有user key");
                return true;
            }else{
                System.out.println("检测到无user key");
                //主要是这条代码,不加的话会出现重定向次数过多的错误
                //我们的代码是拦截/user/** 后面的,所以跳出这个路径就可以了
                response.sendRedirect(request.getContextPath() + "/error/404");
                return false;
            }
        }else{
            num++;
        }
            return true;
    }

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

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值