本文:
SpringでWebアプリを書くときによく使う @RequestParam
について、
備忘録としてざっくりまとめています。
サンプルメソッド一覧
public String getParam(@RequestParam String greeting)
public String getParam(@RequestParam(name = "g") String greeting)
public String getParam(@RequestParam(required = false) String greeting)
public String getParam(@RequestParam(defaultValue = "(未設定)") String greeting)
違いのまとめ
書き方 |
説明 |
パラメータが未指定だったら? |
① @RequestParam
|
パラメータ名は変数名と同じ |
400エラー(MissingServletRequestParameter) |
② @RequestParam(name = "g")
|
パラメータ名を "g" に指定 |
400エラー |
③ @RequestParam(required = false)
|
パラメータはあってもなくてもOK |
null が入る |
④ @RequestParam(defaultValue = "(未設定)")
|
パラメータがなければ "(未設定)" を使う |
"(未設定)" が入る |
① @RequestParam
@GetMapping("/hello")
public String getParam(@RequestParam String greeting)
アクセスURL |
結果 |
備考 |
/hello?greeting=Hi |
Hello, Hi |
OK |
/hello |
❌ 400 Bad Request |
greeting が必須 |
② @RequestParam(name = "g")
@GetMapping("/hello")
public String getParam(@RequestParam(name = "g") String greeting)
アクセスURL |
結果 |
備考 |
/hello?g=Hi |
Hello, Hi |
OK |
/hello |
❌ 400 Bad Request |
g が必須 |
③ @RequestParam(required = false)
@GetMapping("/hello")
public String getParam(@RequestParam(required = false) String greeting)
アクセスURL |
結果 |
/hello?greeting=Hi |
Hello, Hi |
/hello |
Hello, null |
④ @RequestParam(defaultValue = "(未設定)")
@GetMapping("/hello")
public String getParam(@RequestParam(defaultValue = "(未設定)") String greeting)
アクセスURL |
結果 |
/hello?greeting=Hi |
Hello, Hi |
/hello |
Hello, (未設定) |
まとめ
-
必須にしたいなら:
@RequestParam
-
任意にしたいなら:
@RequestParam(required = false)
-
デフォルト値を設定したいなら:
@RequestParam(defaultValue = "...")
-
名前を変えたいなら:
@RequestParam(name = "xxx")
Discussion