添加拦截器类

@Component
public class PermissionInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod method;
    try {
        method = (HandlerMethod) handler;
    } catch (ClassCastException e) {
        return true;
    }
    //获取类上的注解
    Permission permission = method.getBeanType().getAnnotation(Permission.class);
    //若类上没有注解
    if (permission == null) {
        //判断方法上是否存在注解
        permission = method.getMethodAnnotation(Permission.class);
        if (permission == null) {
            return true;
        }
    }

    String token = request.getHeader("token");
    if (ObjectUtils.isEmpty(token)) {
        throw new Exception("帐号尚未登录");
    }

    String sessionStr = (String) RedisUtils.get("token", token);
    if (!ObjectUtils.isEmpty(sessionStr)) {
        return true;
    }

    throw new Exception("帐号尚未登录");
    }
}

权限注解,在类上或者方法上加注解均会拦截

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface Permission {
    /**
     * @return 该接口需要的权限。
     */
    public String[] value() default {};

    /**
     * @return 该接口是否需要登陆后才能使用,默认值为需要。
     */
    public boolean requireLogin() default true;
}

配置拦截路径

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Autowired
private PermissionInterceptor permissionInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    // 添加拦截器,配置拦截地址
    registry.addInterceptor(permissionInterceptor).addPathPatterns("/**");
}
}
最后修改:2021 年 09 月 03 日
如果觉得我的文章对你有用,请随意赞赏