Springboot 1.x集成Sa-Token

本文介绍了如何在保留SpringBoot1.5.9版本的项目中集成Sa-Token1.35.0.RC,通过替换WebMvcConfigurer接口和自定义Interceptor实现注解式鉴权。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

真没想到这么久了, 还有springboot1.x的项目, 依然处于开发阶段…

环境介绍:

  • jdk: 1.8

  • SpringBoot: 1.5.9.RELEASE

  • SaToken: 1.35.0.RC

直接上demo

完整demo见github

这里是sa-token对springboot2.x的demo

image-20230907091654178

这里仅对关键部分写个注释, 解法如下:

  1. 将实现WebMvcConfigurer接口替换为继承WebMvcConfigurerAdapter
  2. 继承SaInterceptor并添加afterCompletionpostHandle两个方法的默认实现(空方法即可)
  3. 正常使用即可
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

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

/**
 * sa-token
 *
 * @author ly-chn
 * @see <a href="https://sa-token.dev33.cn/">官方文档</a>
 */
@Configuration
public class SaTokenConfig extends WebMvcConfigurerAdapter {
    /**
     * 注册Sa-Token的注解拦截器,打开注解式鉴权功能
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler -> {
                    StpUtil.checkLogin();
                }) {
                    @Override
                    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

                    }

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

                    }
                })
                .addPathPatterns("/**")
                .excludePathPatterns("/error", "以及其他登录等等功能");
    }
}

如有问题欢迎继续加入SaToken交流群讨论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值