上一篇 weblfux 主要介紹了 path 參數的解析與映射關係,在我們進入 url 參數/post 表單之前,先看一下另外的一種參數--請求頭中的參數如何處理
I. 項目環境
本項目藉助SpringBoot 2.2.1.RELEASE
+ maven 3.5.3
+ IDEA
進行開發
1. 依賴
使用 WebFlux,最主要的引入依賴如下(省略掉了 SpringBoot 的相關依賴,如對於如何創建 SpringBoot 項目不太清楚的小夥伴,可以關注一下我之前的博文)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
II. 請求頭參數解析
在實際的業務開發中,有幾個請求頭出現的頻率特別高,如常用於反爬的User-Agent
,鑑定強求來源的referer
,跨域相關的Access-Control-Allow-
,cookie、session 自定義的請求頭等
1. 請求頭限制
在RequestMapping
或GetMapping
中指定請求頭參數時,表示只有請求中包含這個請求頭纔會匹配過去
/**
* 只有請求頭包含 myheader 且值爲 myvalue的纔可以訪問到
*
* - 正常訪問: curl 'http://127.0.0.1:8080/header/filter/yihhui' -H 'myheader: myvalue'
* - 異常訪問: curl 'http://127.0.0.1:8080/header/filter/yihhui' -H 'myheader: myvalue2' 因爲請求頭不匹配,404
*
* @param name
* @return
*/
@GetMapping(path = "/filter/{name}", headers = "myheader=myvalue")
public Mono<String> headerFilter(@PathVariable(name = "name") String name) {
return Mono.just("request filter: " + name);
}
實例如下:
➜ ~ curl 'http://127.0.0.1:8080/header/filter/yihhui' -H 'myheader: myvalue'
request filter: yihhui%
➜ ~ curl 'http://127.0.0.1:8080/header/filter/yihhui' -H 'myheader: myvalue2'
{"timestamp":"2020-09-07T00:40:34.493+0000","path":"/header/filter/yihhui","status":404,"error":"Not Found","message":null,"requestId":"aa47f5a5"}%
2. 請求頭參數解析
WebFlux 依然是可以通過註解@RequestHeader
來獲取對應的請求頭
從使用姿勢上來看,webflux 與 webmvc 並沒有什麼區別
/**
* 獲取請求頭
*
* curl 'http://127.0.0.1:8080/header/get' -H 'myheader: myvalue' -H 'user-agent: xxxxxxx'
*
* @param header 注意,這個是自定義的請求頭
* @param userAgent
* @return
*/
@GetMapping(path = "get")
public Mono<String> getHeader(@RequestHeader("myheader") String header,
@RequestHeader("user-agent") String userAgent) {
return Mono.just("request headers: myheader=" + header + " userAgent=" + userAgent);
}
測試 case 如下
➜ ~ curl 'http://127.0.0.1:8080/header/get' -H 'myheader: myvalue' -H 'user-agent: xxxxxxx'
request headers: myheader=myvalue userAgent=xxxxxxx%
3. cookie 獲取
利用 cookie 來標識用戶身份可以說是非常普遍的場景了,我們通過專用的CookieValue
來獲取指定的 cookies 值
/**
* 獲取cookie
*
* curl 'http://127.0.0.1:8080/header/cookie' --cookie 'tid=12343123;tt=abc123def'
*
* @param tid
* @return
*/
@GetMapping(path = "cookie")
public Mono<String> getCookie(@CookieValue("tid") String tid) {
return Mono.just("request cookies tid=" + tid);
}
上面的 case 中,標識只需要獲取 tid 這個 cookies 值,其他的不 care
➜ ~ curl 'http://127.0.0.1:8080/header/cookie' --cookie 'tid=12343123;tt=abc123def'
request cookies tid=12343123%
II. 其他
0. 項目
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源碼: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/223-webflux-params
系列博文
1. 一灰灰 Blog
盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現 bug 或者有更好的建議,歡迎批評指正,不吝感激
下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛
- 一灰灰 Blog 個人博客 https://blog.hhui.top
- 一灰灰 Blog-Spring 專題博客 http://spring.hhui.top