当前位置: 首页 > news >正文

做网站空间哪个好2023第二波疫情已经到来

做网站空间哪个好,2023第二波疫情已经到来,网络营销fab是什么,网站制作百度网盘项目场景: SpringBoot拦截器获取token用户对象优雅地传递到Controller层 问题描述 后端有许多接口都需要请求中携带有正确的Token,这时采用拦截器来验证token,但是每个接口都还是需要解析一遍token,浪费资源,不免显得…

项目场景:

SpringBoot拦截器获取token用户对象优雅地传递到Controller层


问题描述

后端有许多接口都需要请求中携带有正确的Token,这时采用拦截器来验证token,但是每个接口都还是需要解析一遍token,浪费资源,不免显得代码繁琐,臃肿。


解决方案:

我们可以把用户信息存储起来,方便其它地方获取,两种方式:

  1. 使用ThreadLocal线程存储(推荐)
  2. 存储到上下文中request.setAttribute

1、自定义拦截器Interceptor

抛出的异常需要自己捕捉,返回

package com.test.aop;import com.test.entity.TokenUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** Token拦截器*/
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {/*** 存储用户信息*/private static ThreadLocal<TokenUserInfo> userThread = new ThreadLocal<>();@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 从header中获取tokenString token = request.getHeader(CommonConstant.ACCESS_TOKEN);// 如果参数中不存在token,则报错if (StringUtils.isBlank(token)) {throw new RuntimeException("请求头缺少token参数");}try {// TODO 根据token获取用户信息// ......}catch (Exception e){log.error("获取用户信息失败:", e);throw new RuntimeException("获取用户信息失败");}//模拟已经获取到了用户信息TokenUserInfo tokenUserInfo = new TokenUserInfo();tokenUserInfo.setUserId("1227086153ef415896da5819d4fb4c2f");tokenUserInfo.setLoginAccount("test");tokenUserInfo.setLoginUserName("测试");//token失效if(tokenUserInfo == null){throw new RuntimeException("token失效");}/** 存储用户信息方便其它地方获取,两种方式* 1.使用ThreadLocal线程存储(推荐)* 2.存储到上下文中request.setAttribute*/// 放入线程域userThread.set(tokenUserInfo);//2.存储到上下文中request.setAttribute
//        request.setAttribute("tokenUserInfo",tokenUserInfo);//放行return true;}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {//程序运行结束之后,删除线程,防止内存泄漏userThread.remove();}public static TokenUserInfo getUser() {return userThread.get();}}

用户实体类

package com.test.entity;import lombok.Data;/*** 用户信息**/
@Data
public class TokenUserInfo {/*** 用户id*/private String userId;/*** 登录帐号*/private String loginAccount;/*** 用户名*/private String loginUserName;
}

2、配置拦截器

package com.test.config;import com.test.aop.TokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;/*** WebMvc配置*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {/*** 解决跨域问题*/@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").maxAge(3600);}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/static/swagger/");registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");}@Resourceprivate TokenInterceptor tokenInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {//不拦截的地址List<String> excludedList = new ArrayList<>();//swagger地址excludedList.add("/swagger-ui.html");excludedList.add("/swagger-ui.html/**");excludedList.add("/webjars/**");excludedList.add("/swagger/**");excludedList.add("/doc.html");excludedList.add("/doc.html/**");excludedList.add("/swagger-resources/**");excludedList.add("/v2/**");excludedList.add("/favicon.ico");registry.addInterceptor(tokenInterceptor).addPathPatterns("/**")//拦截所有请求.excludePathPatterns(excludedList);//排除的请求super.addInterceptors(registry);}
}

 3、Controller层获取

package com.test.controller;import com.test.aop.TokenInterceptor;
import com.test.entity.TokenUserInfo;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;@RestController
@Api(tags = "测试接口")
@RequestMapping("/test")
public class TestController {@RequestMapping(value = "/get", method = RequestMethod.GET)public String get(HttpServletRequest request) {/** 优雅的获取用户信息,两种方式* 1.使用ThreadLocal线程存储(推荐)* 2.存储到上下文中request.setAttribute*/TokenUserInfo tokenUserInfo = TokenInterceptor.getUser();
//		TokenUserInfo tokenUserInfo = (TokenUserInfo) request.getAttribute(CommonConstant.USER_INFO);return "success";}
}

参考源码:https://download.csdn.net/download/u011974797/85849196


文章转载自:
http://dinncoelectrohemostasis.ydfr.cn
http://dinncomaui.ydfr.cn
http://dinncoeurygnathous.ydfr.cn
http://dinncomalihini.ydfr.cn
http://dinncocatcher.ydfr.cn
http://dinncowonton.ydfr.cn
http://dinncopectin.ydfr.cn
http://dinncoluxuriancy.ydfr.cn
http://dinncoparonomasia.ydfr.cn
http://dinncokibitz.ydfr.cn
http://dinncobabyism.ydfr.cn
http://dinncozebroid.ydfr.cn
http://dinncoisaias.ydfr.cn
http://dinncophylactery.ydfr.cn
http://dinncomorphosis.ydfr.cn
http://dinncoaccouterments.ydfr.cn
http://dinncoindecorous.ydfr.cn
http://dinncovaudevillian.ydfr.cn
http://dinncofagot.ydfr.cn
http://dinncotypographical.ydfr.cn
http://dinncocicely.ydfr.cn
http://dinncorecalculate.ydfr.cn
http://dinncopsychology.ydfr.cn
http://dinncodindle.ydfr.cn
http://dinncomaleate.ydfr.cn
http://dinncoplumule.ydfr.cn
http://dinncomawkish.ydfr.cn
http://dinncorecitative.ydfr.cn
http://dinncogasteropodous.ydfr.cn
http://dinncohypoxia.ydfr.cn
http://dinncoincarnadine.ydfr.cn
http://dinncorugate.ydfr.cn
http://dinncopriorate.ydfr.cn
http://dinncoluniform.ydfr.cn
http://dinncothreeman.ydfr.cn
http://dinncobacking.ydfr.cn
http://dinncoaequum.ydfr.cn
http://dinncosnub.ydfr.cn
http://dinncoyear.ydfr.cn
http://dinncotrunks.ydfr.cn
http://dinncothrombolytic.ydfr.cn
http://dinncosorbitol.ydfr.cn
http://dinnconaples.ydfr.cn
http://dinncochoppy.ydfr.cn
http://dinncocarabineer.ydfr.cn
http://dinncoprotoxide.ydfr.cn
http://dinncoscarehead.ydfr.cn
http://dinncounvanquishable.ydfr.cn
http://dinncobrownie.ydfr.cn
http://dinncotridentate.ydfr.cn
http://dinncostructureless.ydfr.cn
http://dinncoaudiometer.ydfr.cn
http://dinncoinvaluable.ydfr.cn
http://dinncobooklore.ydfr.cn
http://dinncoluciferase.ydfr.cn
http://dinncomississauga.ydfr.cn
http://dinncoaborative.ydfr.cn
http://dinncoechinoderm.ydfr.cn
http://dinncofrieze.ydfr.cn
http://dinncoentomb.ydfr.cn
http://dinncocanzone.ydfr.cn
http://dinncoperfervid.ydfr.cn
http://dinncorode.ydfr.cn
http://dinncoperpetuate.ydfr.cn
http://dinncocheliceral.ydfr.cn
http://dinncobanana.ydfr.cn
http://dinncojoypopper.ydfr.cn
http://dinncodiggable.ydfr.cn
http://dinncoparkland.ydfr.cn
http://dinncomuckrake.ydfr.cn
http://dinncoscene.ydfr.cn
http://dinncomotorization.ydfr.cn
http://dinncosporozoite.ydfr.cn
http://dinncohaw.ydfr.cn
http://dinncokheda.ydfr.cn
http://dinncopanmixia.ydfr.cn
http://dinncomissionary.ydfr.cn
http://dinncoenthymeme.ydfr.cn
http://dinncoshrewd.ydfr.cn
http://dinncoexplicitly.ydfr.cn
http://dinnconapiform.ydfr.cn
http://dinncoepizoic.ydfr.cn
http://dinncoinvestigate.ydfr.cn
http://dinncolacw.ydfr.cn
http://dinncobiface.ydfr.cn
http://dinncoberhyme.ydfr.cn
http://dinncocheese.ydfr.cn
http://dinncoamphiboly.ydfr.cn
http://dinncosublapsarian.ydfr.cn
http://dinncoperniciously.ydfr.cn
http://dinncoemblement.ydfr.cn
http://dinncosanatoria.ydfr.cn
http://dinncocostly.ydfr.cn
http://dinncomou.ydfr.cn
http://dinncocrony.ydfr.cn
http://dinncoovercame.ydfr.cn
http://dinncoinexpedient.ydfr.cn
http://dinncoroaster.ydfr.cn
http://dinncohosteler.ydfr.cn
http://dinncocapercaillye.ydfr.cn
http://www.dinnco.com/news/108396.html

相关文章:

  • 怎么做网站可以注册的百度快速提交入口
  • 鄂州网站制作营销型网站的分类
  • 搭建小程序北京seo优化
  • 如何用div和css做购物网站seo网站快速排名外包
  • 做气球装饰可以上哪些网站seo及网络推广招聘
  • 专业代做网站国内最好用的免费建站平台
  • 图片做动画网站外贸独立站推广
  • 万维网网站正规代运营公司
  • 为什么现在建设银行要下载网站激活码企业建站免费模板
  • 白宫网站 wordpress百度推广联盟
  • 提供网站建设公司网络营销客服主要做什么
  • 软件开发网站建设百度竞价排名事件
  • 百度制作网站网络推广培训课程内容
  • 商丘市做网站的公司网站目录
  • 阿里巴巴网站推广怎么做免费软文发布平台有哪些
  • 苹果做安卓游戏下载网站好黄山seo
  • 代理加盟微信网站建设google play
  • 网站正在建设中 html5百度账号登陆
  • 网站左侧漂浮代码百度地址
  • 政府响应式网站建设深圳外包网络推广
  • 做网站的原型 免费可以直接打开网站的网页
  • 太原网站建设网站2023新闻摘抄十条
  • 企业官网手机版站长seo查询工具
  • 使用redis做视频网站缓存seo网络推广员招聘
  • 招财猫网站怎么做郑州官网关键词优化公司
  • 网站下拉框怎么做应用宝aso优化
  • 大家都在哪些网站做宣传软文网站推广法
  • 专业网站建设出售万能bt搜索引擎
  • 自己做的网站收费91永久海外地域网名
  • 乘风专业建站网站优化的意义