Home > front end >  Spring MVC : redirect from POST to GET with attributes
Spring MVC : redirect from POST to GET with attributes

Time:03-20

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";
}

CodePudding user response:

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.addAttribute("mode", mode);
    redirectedAttributes.addAttribute("boardSize", resettedGame.getBoardSize());
    redirectedAttributes.addAttribute("moves", getJSONMoves(resettedGame.getMoves()).toString());
    
    return new ModelAndView("redirect:/board");
}

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";
}
  • Related