springmvc优雅地将拦截器中的对象传递到controller或service中

1.可以使用request 携带数据。但springmvc不推荐;

2.使用Threadlocal线程,请求产生响应前,处于同一个线程中。

比如在一个登录拦截器中,在preHandle方法中登录成功后,放行前,想把user对象传到controller或service中

新建类 LoginInterceptor

public class LoginInterceptor extends HandlerInterceptorAdapter {

    private JwtProperties jwtProperties;
    private JwtProperties jwtProperties;

    // 定义一个线程域,存放登录用户
    private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();

    public LoginInterceptor(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 查询token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        if (StringUtils.isBlank(token)) {
            // 未登录,返回401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        // 有token,查询用户信息
        try {
            // 解析成功,证明已经登录
            UserInfo user = JwtUtils.getUserInfo(jwtProperties.getPublicKey(),token);
            // 放入线程域
            tl.set(user);
            //request.setAttribute("user", user);
            return true;
        } catch (Exception e){
            // 抛出异常,证明未登录,返回401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //程序运行结束之后,删除线程
        tl.remove();
    }

    public static UserInfo getLoginUser() {
        return tl.get();
    }
}
  • 这里我们使用了ThreadLocal来存储查询到的用户信息,线程内共享,因此请求到达Controller后可以共享User
  • 并且对外提供了静态的方法:getLoginUser()来获取User信息

配置springmvc,使拦截器

@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    private JwtProperties jwtProperties;

    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor(jwtProperties);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor()).addPathPatterns("/**");
    }
}

 

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值