REST with Spring Boot 2
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Hello, REST!
Spring Boot 創建 REST API 的方法
- 創一個 Class
- Class 上面加上
@RestController
的 annotation - Class 裡面創一個 public method
- Method 上面加上
@RequestMapping
的 annotation - 替
@RequestMapping
加上 REST API 的設定value
: URL 位址,例如"/hello"
produces
: 回傳的類型,例如回傳 JSON 的話就填上MediaType.APPLICATION_JSON_VALUE
method
: Request 的 method,例如 GET 的話就寫RequestMethod.GET
- 這個 method 回傳的 Java POJO,就會自動被轉換成對應的 JSON 並回傳
下面的練習,請試著回傳一個 Java POJO,並在 answer 裡面填上 "Hello, REST!"
Complete the controller to say "Hello, REST!"
1
10
11
12
13
14
15
16
17
18
19
20
21
// {
@RestController
public class QuizController01 {
@RequestMapping(value = "/restQuiz01", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public RestQuiz01Response restQuiz01() {
// TODO: Please return JSON with {"answer": "Hello, REST!"}
RestQuiz01Response result = new RestQuiz01Response();
result.setAnswer("5566 Never Dies.");
return result;
}
}
Enter to Rename, Shift+Enter to Preview
1
package com.example.training.to;
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content