springboot項目獲取請求頭當中的token的方法
一.直接在controller層當中直接獲取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è)務層獲取token
在service層中獲取token需要使用相應的工具類,這里我分享一個有用的工具類。代碼如下:
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:
直接在相應的service業(yè)務層中使用工具類獲取當前請求的token
String token = UserRequest.getCurrentToken();
到此這篇關于springboot項目獲取請求頭當中的token的方法的文章就介紹到這了,更多相關springboot獲取請求頭token內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
如何在Spring Boot應用中優(yōu)雅的使用Date和LocalDateTime的教程詳解
這篇文章主要介紹了如何在Spring Boot應用中優(yōu)雅的使用Date和LocalDateTime,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
聊聊Spring?Boot如何配置多個Kafka數(shù)據(jù)源
這篇文章主要介紹了Spring?Boot配置多個Kafka數(shù)據(jù)源的相關知識,包括生產(chǎn)者、消費者配置,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-10-10
IntelliJ IDEA創(chuàng)建maven多模塊項目(圖文教程)
這篇文章主要介紹了IntelliJ IDEA創(chuàng)建maven多模塊項目(圖文教程),非常具有實用價值,需要的朋友可以參考下2017-09-09

