How to receive path variables in Spring, how to pass to redirect destination Memo
// (1)
@GetMapping("{name}")
public String detail(@PathVariable String name) {
return "detail";
}
// (2)
@GetMapping("idol/{name}")
public String idolDetail(@PathVariable("name") String idolName) {
return "idol/detail";
}
// (3)
@GetMapping("unit/{unitId}/idol/{idolId}")
public String idolDetail(@PathVariable("unitId") Integer unitId, @PathVariable("idolId") Integer idolId) {
return "idol/detail";
}
If you want to use the value contained in the path in the process of the method, use the path variable ({variable name}
) format in the part where the value you want to receive is entered in the Mapping annotation, and set the corresponding argument to @PathVariable. Specify
.
(1) If the path variable name and the variable name actually used are the same, the value attribute of @PathVariable
can be omitted.
(2) If the variable name is different, specify the path variable name in the value attribute of @PathVariable
.
(3) Multiple is possible.
// (1)
@PostMapping("idol/{name}/update")
public String update(@PathVariable String name) {
return "redirect:/idol/{name}";
}
// (2)
@PostMapping("redirect")
public String redirect(RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("name", "Jinka Osaki");
return "redirect:/idol/{name}";
}
(1)
A variable once received as a path variable can be passed to the redirect destination as it is.
In the case of the above code, if you send a POST request to / idol / Kiriko Yuya / update
, the URL of the redirect destination will be / idol / Kiriko Yuya
.
(2)
If the variable added by using the ʻaddAttributemethod of RedirectAttributes is included in the redirect destination path variable, it is expanded as it is as a path variable. In the above case, the redirect destination URL will be
/ idol / Osaki Jinka`.
(2) may be a simple string concatenation if it is not necessary to enter a value separately.
Official Reference Spring MVC controller arguments Thorough introduction to Spring Java application development with Spring Framework
Recommended Posts