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.
POST parameters
POST method 的 REST 創建方式和 GET 雷同。
- 在 method 前面的 @RequestMapping裡面,改成method = RequestMethod.POST
- 在 method 的參數中,改成接收 @RequestBody,並對應 JSON 的一個 POJO
/* 對應一個 JSON 定義如下
 * {
 *   name: string;
 *   value: number;
 * }
 * 的 POJO 為
 */
public class RequestPOJO {
    private String name;
    private Long number;
    // getter, setter for name & number
}
// 而該 POST API 則如下定義
@RequestMapping(value = "/post", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public void restQuiz04(@RequestBody RequestPOJO request) {
    String name = request.getName();
    Long number = request.getNumber();
}
這邊我們的 POST method 傳入的 content type 是 JSON,還有另一種以前很常見的 form post,這邊就不介紹 form 格式的 POST REST API 寫法了。
下面的練習,請在 REST API 上加入一個 POST 參數,參數物件 type 為 RestQuiz04Request。
- 傳入的 POST JSON 格式為 {name: string;}
- 請實作 RestQuiz04Request物件,使其符合上述的 POST JSON 格式。
- 請實作 restQuiz04,從RestQuiz04Request中取出name,並用RestQuiz01Response回傳Hello, %name%!。
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
// {
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.RestController;
//}
@RestController
public class QuizController04 {
    @RequestMapping(value = "/restQuiz04", produces = MediaType.APPLICATION_JSON_VALUE /* TODO: set method */)
    public RestQuiz01Response restQuiz04(/* TODO: POST Parameter RestQuiz04Request */) {
        // TODO: Read "name" from POST parameter, response with "Hello, %name%!"
        return null;
    }
}
Press desired key combination and then press ENTER.
1
package com.example.training.to;
Press desired key combination and then press ENTER.
1
package com.example.training.to;
Press desired key combination and then press ENTER.
如果傳入的 JSON 是 {},RestQuiz04Request 裡面的 name 會是什麼值呢?
  Open Source Your Knowledge: become a Contributor and help others learn. Create New Content