跳转至

@RequestParam

name(or value): 指定url 參數的名字 (很少使用)

GET http://localhost:8080/test?testId=36

@RestController
public class MyController3 {
    @RequestMapping("/test")
    public String test(@RequestParam(name = "testId") Integer id) {
        System.out.println("id: " + id);
        return "hello test1";
    }
}

required: 是否是必須的參數 (預設是true)

(required= false) 可以不帶後面的參數

@RestController
public class MyController3 {
    @RequestMapping("/test")
    public String test(@RequestParam(required= false) Integer id) {
        System.out.println("id: " + id);
        return "hello test1";
    }
}

required 測試

@RestController
public class MyController3 {
    @RequestMapping("/test")
    public String test2(@RequestParam Integer id,
                        @RequestParam(required = false) String name) {
        System.out.println("id: " + id);
        System.out.println("name: " + name);
        return "hello test1";
    }
}

Talend API Tester

需要2個參數 但這邊只傳1個參數 ,name 加上了required 變成非必要參數

http://localhost:8080/test?id=36

200

console:

id:36
name:null

name這個參數的值不會被忽略 ,顯示了null 所以需要注意 NullPointerException

defaultValue: required= false 的加強版 ,提供預設值

  • 可以避免掉參數可能為 null 的情況

會優先以 url 裡面的參數去取得

defaultValue 是 @RequestParam 最常使用的設定

@RestController
public class MyController3 {
    @RequestMapping("/test")
    public String test5(@RequestParam(defaultValue = "10") Integer id) {
        System.out.println("id: " + id);
        return "hello test1";
    }
}

Talend API Tester

加上預設值

GET http://localhost:8080/test

console:

id: 10

"設定" 同時使用也是可以的 ,中間加個逗號即可 ,沒有順序性

@RestController
public class MyController3 {
    @RequestMapping("/test")
    public String test6(@RequestParam(defaultValue = "10" ,name = "testId") Integer id) {
        System.out.println("id: " + id);
        return "hello test1";
    }
}