Spring MVC:从 POST 重定向到具有属性的 GET

Spring MVC : redirect from POST to GET with attributes

我对 Spring MVC 很陌生。我想将模型属性从我的 POST 方法传递给 GET 方法。我该怎么做?

这是我的 POST 服务:

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

这是我的GET服务,POST方法中定义的属性没有传递给GET方法。有谁能够帮助我 ? =)

@GetMapping("/board")
public String board() {
    return "board";
}

使用 RedirectAttributes 来实现。

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

根据文档,flash 属性执行以下操作。

After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL.

get 方法中,单独或通过模型使用参数。

假设 boardSize 是整数且永不为空;

@GetMapping("/board")
public String board(@RequestParam String mode, @RequestParam int boardSize, @RequestParam String moves) {

    return "board";
}