Spring Boot中的六種API請(qǐng)求參數(shù)讀取方式
使用Spring Boot開(kāi)發(fā)API的時(shí)候,讀取請(qǐng)求參數(shù)是服務(wù)端編碼中最基本的一項(xiàng)操作,Spring Boot中也提供了多種機(jī)制來(lái)滿足不同的API設(shè)計(jì)要求。
接下來(lái),就通過(guò)本文,為大家總結(jié)6種常用的請(qǐng)求參數(shù)讀取方式。如果你發(fā)現(xiàn)自己知道的不到6種,那么趕緊來(lái)查漏補(bǔ)缺一下。如果你知道的不止6種,那么告訴大家,一起互相學(xué)習(xí)一下吧~
#@RequestParam
這是最最最最最最常用的一個(gè)了吧,用來(lái)加載URL中?之后的參數(shù)。
比如:這個(gè)請(qǐng)求/user?name=didispace 就可以如下面這樣,使用@RequestParam來(lái)加載URL中的name參數(shù)
@GetMapping("/user")
@ResponseBody()
public User findUserByName(@RequestParam("name") String name){
return userRepo.findByName(name);
}
#@PathVariable
這是RESTful風(fēng)格API中常用的注解,用來(lái)加載URL路徑中的參數(shù)
比如:這個(gè)請(qǐng)求/user/1 就可以如下面這樣,使用@PathVariable來(lái)加載URL中的id參數(shù)
@GetMapping("/user/{id}")
@ResponseBody()
public User findUserById(@PathVariable("id") String id){
return userRepo.findById(id);
}
#@MatrixVariable
這個(gè)我們用的并不是很多,但一些國(guó)外系統(tǒng)有提供這類API參數(shù),這種API的參數(shù)通過(guò);分割。
比如:這個(gè)請(qǐng)求/books/reviews;isbn=1234;topN=5; 就可以如下面這樣,使用@MatrixVariable來(lái)加載URL中用;分割的參數(shù)
@GetMapping("/books/reviews")
@ResponseBody()
public List<BookReview> getBookReviews(
@MatrixVariable String isbn, @MatrixVariable Integer topN) {
return bookReviewsLogic.getTopNReviewsByIsbn(isbn, topN);
}
#@RequestBody
這也是最常用的一個(gè)注解,用來(lái)加載POST/PUT請(qǐng)求的復(fù)雜請(qǐng)求體(也叫:payload)。比如,客戶端需要提交一個(gè)復(fù)雜數(shù)據(jù)的時(shí)候,就要將這些數(shù)據(jù)放到請(qǐng)求體中,然后服務(wù)端用@RequestBody來(lái)加載請(qǐng)求體中的數(shù)據(jù)
@PostMapping("/add")
public boolean addAccounts(@RequestBody List<Account> accounts) throws SQLException {
accounts.stream().forEach(a -> {
a.setCreatedOn(Timestamp.from(Instant.now()));
a.setLastLogin(Timestamp.from(Instant.now()));
});
return notificationLogic.addAccounts(accounts);
}
#@RequestHeader
@RequestHeader注解用來(lái)加載請(qǐng)求頭中的數(shù)據(jù),一般在業(yè)務(wù)系統(tǒng)中不太使用,但在基礎(chǔ)設(shè)施的建設(shè)中會(huì)比較常用,比如傳遞分布式系統(tǒng)的TraceID等。用法也很簡(jiǎn)單,比如,假設(shè)我們將鑒權(quán)數(shù)據(jù)存在http請(qǐng)求頭中,那么就可以像下面這樣用@RequestHeader來(lái)加載請(qǐng)求頭中的Authorization參數(shù)
@GetMapping("/user")
@ResponseBody()
public List<User> getUserList(@RequestHeader("Authorization") String authToken) {
return userRepo.findAll();
}
#@CookieValue
當(dāng)我們需要與客戶端保持有狀態(tài)的交互時(shí),就需要用到Cookie。此時(shí),服務(wù)端讀取Cookie數(shù)據(jù)的時(shí)候,就可以像下面這樣用@CookieValue來(lái)讀取Cookie中的SessionId數(shù)據(jù)
@GetMapping("/user")
@ResponseBody()
public List<User> getUserList(@CookieValue(name = "SessionId") String sessionId) {
return userRepo.findAll();
}
好了,今天的分享就到這里。這些方式你都知道嗎?
https://www.didispace.com/article/spring-boot/spring-boot-rest-api-6-ways-to-pass-params.html