springboot項目獲取請求頭當(dāng)中的token的方法
一.直接在controller層當(dāng)中直接獲取token
在controller層獲取前端在請求頭中存儲的token有兩種方式:
獲取token方式1
/** * 獲取請求頭中的token方式一 * @param request * @return */ @GetMapping("/testGetToken") private apiResult getToken(HttpServletRequest request){ String token = request.getHeader("token"); return apiResult.ok(token); }
獲取token方式2
/** * 獲取請求頭中的token方式二 * @param token * @return */ @GetMapping("/testGetTokenTwo") private apiResult getTokenTwo(@RequestHeader("token") String token){ return apiResult.ok(token); }
二.在service業(yè)務(wù)層獲取token
在service層中獲取token需要使用相應(yīng)的工具類,這里我分享一個有用的工具類。代碼如下:
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * 獲取請求頭中的token工具類 */ public class UserRequest { public static String getCurrentToken() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest(); String token = request.getHeader("token"); return token; } }
那么這個工具類如何使用呢?很簡單,使用方法如下:
獲取token方式3:
直接在相應(yīng)的service業(yè)務(wù)層中使用工具類獲取當(dāng)前請求的token
String token = UserRequest.getCurrentToken();
到此這篇關(guān)于springboot項目獲取請求頭當(dāng)中的token的方法的文章就介紹到這了,更多相關(guān)springboot獲取請求頭token內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring?Boot?Jwts?Token生成方法示例
- 在SpringBoot中使用jwt實(shí)現(xiàn)token身份認(rèn)證的實(shí)例代碼
- SpringBoot?jwt的token如何刷新
- springboot 整合 sa-token簡介及入門教程
- SpringBoot實(shí)現(xiàn)JWT token自動續(xù)期的示例代碼
- SpringBoot Security實(shí)現(xiàn)單點(diǎn)登出并清除所有token
- springboot后端如何實(shí)現(xiàn)攜帶token登陸
- SpringBoot登錄驗證token攔截器的實(shí)現(xiàn)
- SpringBoot整合token實(shí)現(xiàn)登錄認(rèn)證的示例代碼
相關(guān)文章
如何在Spring Boot應(yīng)用中優(yōu)雅的使用Date和LocalDateTime的教程詳解
這篇文章主要介紹了如何在Spring Boot應(yīng)用中優(yōu)雅的使用Date和LocalDateTime,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07聊聊Spring?Boot如何配置多個Kafka數(shù)據(jù)源
這篇文章主要介紹了Spring?Boot配置多個Kafka數(shù)據(jù)源的相關(guān)知識,包括生產(chǎn)者、消費(fèi)者配置,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-10-10高分面試分析jvm如何實(shí)現(xiàn)多態(tài)
這篇文章主要介紹了講解了在面試中jvm如何實(shí)現(xiàn)多態(tài),怎樣回答才能得到高分的問題分析,有需要的朋友可以借鑒參考下,祝大家早日升職加薪多多進(jìn)步2022-01-01IntelliJ IDEA創(chuàng)建maven多模塊項目(圖文教程)
這篇文章主要介紹了IntelliJ IDEA創(chuàng)建maven多模塊項目(圖文教程),非常具有實(shí)用價值,需要的朋友可以參考下2017-09-09IDEA JAVA項目熱加載的實(shí)現(xiàn)步驟
熱加載可以使代碼修改后無須重啟服務(wù)器,就可以加載更改的代碼,本文主要介紹了IDEA JAVA項目熱加載的實(shí)現(xiàn)步驟,具有一定的參考價值,感興趣的可以了解一下2023-06-06