Spring BootのGETリクエストでパラメータを設定した時、
パラメータを取得するには@PathVariableを使います。
例えば以下のような@RequestMappingがあった場合、idは必須になります。
@RequestMapping(value="top/{id}", method = RequestMethod.GET) String topForm(@PathVariable("id") Integer id, Model model) {
しかし、以下のようなtopもtop/{id}も同一の@RequestMappingを通したい時、
@RequestMapping(value={"top", "top/{id}"}, method = RequestMethod.GET) String topForm(@PathVariable("id") Integer id, Model model) {
@PathVariable("id")を設定している以上、idが必須にも関わらず、
「/top」の場合でも@RequestMappingの対象になってしまい、パラメータがないというエラーが速攻で出ます。
なので、topもtop/{id}も同一の@RequestMappingを通したい場合、パラメータを必須にしない設定をしたいです。
やり方としては色々ありますが、一つの方法としてOptionalを使う方法があります。
@RequestMapping(value={"top", "top/{id}"}, method = RequestMethod.GET) String topForm(@PathVariable Optional<Integer> param, Model model) {
引数はオプション扱いなので必ずしも必要にならないんですね。
いざidの値を取得したい時は、以下のようにget()を使えば取得できます。
if (param.isPresent()) {
Integer id = param.get();
・
・
・
}
これで引数を必須とせず、topもtop/{id}も同一の@RequestMappingを通すことができるのです。