springboot拦截器预处理请求

1.创建LoginRequired和ReturnPage注解,分别表示 是否需要登录来访问 和 返回数据还是页面(因为我没怎么学前端只会new Vue(..) 所以只引入了个vue.js和axios.js 没法通过this.$router.push切换页面)。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReturnPage {
}

2.实现WebMvcConfigurer 加上Configuration注解 添加放行和拦截

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] addPath = {"/**"};
        String[] excludePath = {"/login", "/", "/swagger-ui"};
        registry.addInterceptor(new MyInterceptor()).addPathPatterns(addPath).excludePathPatterns(excludePath);
    }
}

3.没啥好说的

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) { //这样写静态资源好像都放行了就不用在上面exclude path里加了
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        if (loginRequired == null) { //没有加LoginRequired注解 就不用管了
            return true;
        }
        Cookie[] cookies = request.getCookies(); //我是把token存在cookies里 根据实际修改
        for (Cookie cookie: cookies) {
            if (cookie.getName().equals("token")) {
                String token = cookie.getValue();
                System.out.println("Token: " + token);
                if (StringUtils.isBlank(JwtUtils.getUserIdByJwtToken(token))) {
                    System.out.println("登录过期");
                    throw new GlobalException(20002, "登录信息过期,请重新登录");
                } else {
                    return true;
                }
            }
        }
        ReturnPage returnPage = method.getAnnotation(ReturnPage.class);
        if (returnPage == null) { //返回形式是数据 抛异常让GlobalExceptionHandler处理返回json消息
            System.out.println("登录过期");
            throw new GlobalException(20002, "操作异常,请重新登录");
        } else { //访问/login路径 返回到page/login.html
            response.sendRedirect("/login");
            return false;
        }
    }
}

上一篇:MetaFormer才是计算机视觉真正需要的


下一篇:学生基本信息录入系统