iT邦幫忙

2023 iThome 鐵人賽

DAY 18
1
Software Development

Spring Boot 零基礎入門系列 第 18

Spring Boot 零基礎入門 (19) - 取得請求參數(上)- @RequestParam、@RequestBody

  • 分享至 

  • xImage
  •  

@RequestParam:接住添加在 url 後面的參數


@ReqeustParam 的用途,就是「接住那些放在 url 後面的參數」,因此當前端使用 GET 來請求時,我們就可以在 Spring Boot 中寫上 @ReqeustParam,去接住前端所傳遞過來的參數(query parameter)。

@RestController
public class MyController {

    @RequestMapping("/test1")
    public String test1(@RequestParam Integer id) {
        System.out.println("id 的值為: " + id);
        return "請求成功";
    }
}

運行成功之後回到 API Tester 上,接著在 Http method 中選擇 GET 請求,url 填上 http://localhost:8080/test1?id=123 ,這樣子就可以模擬前端的請求。

@RequestBody:接住放在 request body 中的參數


@RequestBody 的用途,就是「接住放在 request body 中的參數」,因此當前端使用 POST 來請求時,我們就可以在 Spring Boot 中寫上 @ReqeustBody,去接住前端放在 request body 中所傳遞的參數。

如果我們想要在 Spring Boot 中去接住這個 JSON 格式的參數的話,那我們首先要做的,就是先去創建一個 Java class 出來,並且這個 Java class 中的變數,會和 JSON 格式的數據「一一對應」。

像是我們可以先去 new 一個 Student class 出來,並且在 Student 中添加下列的程式:

public class Student {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

寫好 Student class 之後,接著我們可以回到 MyController,並且在裡面新增另一個方法 test2(),接著我們在 test2() 中先新增一個 Student 類型的參數 student,並且在這個 name 的前面,加上一個 @RequestBody,如下方程式所示:

@RequestMapping("/test2")
public String test2(@RequestBody Student student) {
    System.out.println("student 中的 id 值為: " + student.getId());
    System.out.println("student 中的 name 值為: " + student.getName());
    return "請求成功";
}

當我們這樣寫之後,Spring Boot 到時候就會將 request body 中的 JSON 參數,自動轉換成我們自定義的 STudent class 了,因此我們後續就可以直接從 test2() 中的 student 參數,直接取得到前端所傳遞過來的 JSON 數據了!

寫上上述的程式之後,可以重新運行一下 Spring Boot 程式,讓這段程式生效。

運行成功之後回到 API Tester 上,接著在 Http method 中選擇 POST 請求,url 填上 http://localhost:8080/test2 ,並且在 request body 中填上下列的 JSON 參數,這樣就可以模擬前端的請求。

{
    "id": 123,
    "name": "Judy"
}

上一篇
Spring Boot 零基礎入門 (18) - 常見的 Http method - GET 和 POST
下一篇
Spring Boot 零基礎入門 (20) - 取得請求參數(下)- @RequestHeader、@PathVariable
系列文
Spring Boot 零基礎入門29
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言