@RequestHeader以及@CookieValue這兩個注解用法類似,屬性也相同,所以,寫在一起。二者屬性和RequestParam的屬性一樣,用法也幾乎一樣。
作用
@RequestHeader注解主要是將請求頭的信息區數據,映射到功能處理方法的參數上。@CookieValue注解主要是將請求的Cookie數據,映射到功能處理方法的參數上。
屬性說明
Annotation which indicates that a method parameter should be bound to an HTTP cookie.
它將一個HTTP cookie綁定於方法的一個參數。
1、value:綁定的參數名稱,String類型。
2、required:是否必須包含value,boolean類型,默認為 true,表示請求參數中必須包含對應的參數;若不存在,將拋出異常。
3、defaultValue:默認值,String類型。當沒有傳參時將使用此值賦值。
案例分析
二者在開發中很少被用到,了解即可。下面的代碼示例演示了如何獲取cookie JSESSIONID,Accept和User-agent 的值:
@RestController @RequestMapping("/user") public class UserController { @RequestMapping("/displayHeaderInfo") public Map<String, Object> displayHeaderInfo(@RequestHeader("User-agent") String userAgent, @RequestHeader(value = "Accept") String[] accepts, @CookieValue("JSESSIONID") String cookie) { Map<String, Object> response = new HashMap<>(); response.put("accepts", accepts); response.put("userAgent", userAgent); response.put("cookie", cookie); return response; } }
postman調試結果如下:
轉載於:https://www.cnblogs.com/east7/p/10303180.html
@RequestHeader以及@CookieValue這兩個注解用法類似,屬性也相同,所以,寫在一起。二者屬性和RequestParam的屬性一樣,用法也幾乎一樣。
作用
@RequestHeader注解主要是將請求頭的信息區數據,映射到功能處理方法的參數上。@CookieValue注解主要是將請求的Cookie數據,映射到功能處理方法的參數上。
屬性說明
Annotation which indicates that a method parameter should be bound to an HTTP cookie.
它將一個HTTP cookie綁定於方法的一個參數。
1、value:綁定的參數名稱,String類型。
2、required:是否必須包含value,boolean類型,默認為 true,表示請求參數中必須包含對應的參數;若不存在,將拋出異常。
3、defaultValue:默認值,String類型。當沒有傳參時將使用此值賦值。
案例分析
二者在開發中很少被用到,了解即可。下面的代碼示例演示了如何獲取cookie JSESSIONID,Accept和User-agent 的值:
@RestController @RequestMapping("/user") public class UserController { @RequestMapping("/displayHeaderInfo") public Map<String, Object> displayHeaderInfo(@RequestHeader("User-agent") String userAgent, @RequestHeader(value = "Accept") String[] accepts, @CookieValue("JSESSIONID") String cookie) { Map<String, Object> response = new HashMap<>(); response.put("accepts", accepts); response.put("userAgent", userAgent); response.put("cookie", cookie); return response; } } |
postman調試結果如下: