REST with Spring Boot 2
Nierrrrrrr
30.2K views
GET parameters
上面的練習中,我們成功的創建出一個 GET method 的 REST API,不過他沒有接入任何的參數,如果要讓 GET method 能夠接收參數,只需要修改 method 的參數就可以了。
- 在 method 的參數加上
String
型別的參數 - 在參數的前面加上
@RequestParam("paramName")
的 annotation,並傳入一個 String 當作 GET 參數的名稱 - 如果這個 GET method 需要接收多個參數,只需要重複上述步驟,設定多個 method 參數即可
假設我們要讓 URL 長的像這樣: /api?param1=Yoyo¶m2=Yee
,method 的定義就會像是
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public void api(@RequestParam("param1") String param1, @RequestParam("param2") String param2) {
// param1 = "Yoyo"
// param2 = "Yee"
}
下面的練習,請在 REST API 上加入一個 GET 參數,並回傳相對應的 answer。
Complete the controller to say "Hello, %name%!"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// {
package com.example.training.rest;
import com.example.training.to.RestQuiz01Response;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
//}
@RestController
public class QuizController02 {
@RequestMapping(value = "/restQuiz02", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public RestQuiz01Response restQuiz02(/* TODO: add GET parameter "name" here */) {
// TODO: Please return JSON with {"answer": "Hello, %name%!"}
RestQuiz01Response result = new RestQuiz01Response();
result.setAnswer("5566 Never Dies.");
return result;
}
}
1
package com.example.training.to;
要注意的是,如果定義了 GET 參數,但是 client 呼叫 REST API 的時候卻沒有帶上,對應的值,我們的 REST API 並不會被真的呼叫,而是會回傳 HTTP 400 回去。因為預設 GET 參數是 required 的。
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds