Issue
I am quite new with Spring MVC. I would like to pass the model attributes from my POST method to the GET method. How could I do this ?
This is my POST service:
@PostMapping("reset-game")
public ModelAndView resetGame(@RequestBody String body, Model model) {
String[] args = body.split("&");
String mode = "";
for (String arg : args) {
if ("mode".equals(arg.split("=")[0])) {
mode = arg.split("=")[1];
break;
}
}
Game resettedGame = gameService.resetGame(mode);
model.addAttribute("mode", mode);
model.addAttribute("boardSize", resettedGame.getBoardSize());
model.addAttribute("moves", getJSONMoves(resettedGame.getMoves()).toString());
return new ModelAndView("redirect:/board");
}
And this is my GET service, the attributes defined in POST method are not passed to the GET method. Can anybody help me ? =)
@GetMapping("/board")
public String board() {
return "board";
}
Solution
Use RedirectAttributes
to achieve this.
@PostMapping("reset-game")
public ModelAndView resetGame(@RequestBody String body, RedirectAttributes redirectedAttributes) {
String[] args = body.split("&");
String mode = "";
for (String arg : args) {
if ("mode".equals(arg.split("=")[0])) {
mode = arg.split("=")[1];
break;
}
}
Game resettedGame = gameService.resetGame(mode);
redirectedAttributes.addFlashAttribute("mode", mode);
redirectedAttributes.addFlashAttribute("boardSize", resettedGame.getBoardSize());
redirectedAttributes.addFlashAttribute("moves", getJSONMoves(resettedGame.getMoves()).toString());
return new ModelAndView("redirect:/board");
}
From the docs, flash attributes does the following.
After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL.
On the get
method, consume the parameters individually or via a model.
Assuming boardSize is integer and never null;
@GetMapping("/board")
public String board(@RequestParam String mode, @RequestParam int boardSize, @RequestParam String moves) {
return "board";
}
Answered By - atish.s
Answer Checked By - Senaida (JavaFixing Volunteer)