Spring boot系列(五)Controller-Parameter


Posted by newstart1117 on 2022-03-18

Controller帶入參數的方式



RequestParam

@GetMapping("/param1")
public String param1(@RequestParam(value = "name", defaultValue = "Sung") String name){
    return "param1: " + name;
}

@GetMapping("/param2")
public String param2(@RequestParam String name){
    return "param2: " + name;
}

瀏覽器呼叫方式:

其中value是參數名稱,defaultValue是預設值,如果沒使用預設值,忘記帶變數就會報錯


PathParam

與上述RequestParam很相似


PathVariable

與上述兩種不同,上述可以透過form發送請求,而此方式是透過URL獲得參數

@GetMapping("/param2")
public String param2(@RequestParam String name){
    return "param2: " + name;
}
@GetMapping("/param3/{name}")
public String param3(@PathVariable String name){
    return "param3: " + name;
}

瀏覽器呼叫方式:


總結一下

RequestParam PathParam PathVariable
可透過URL?帶參數,也可透過form發送 可透過URL?帶參數,也可透過form發送 透過URL/的方式帶參數
user?name=xxx&age=yy user?name=xxx&age=yy user/{name}/{age}
ab+c => ab c ab+c => ab c ab+c => ab+c
可使用required、defauleValue 可使用required、defauleValue X

#java #spring boot #Backend #controller #parameter







Related Posts

[BE201] Express & Sequelize part 3

[BE201] Express & Sequelize part 3

JavaScript 程式執行原理:hw4:What is this?

JavaScript 程式執行原理:hw4:What is this?

【Vue 學習筆記】元件化

【Vue 學習筆記】元件化


Comments