java 如何在不重定向的情况下访问另一个控制器的参数?Spring

ctrmrzij  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(86)

控制器:

@GetMapping("/reservations/chooseExpert")
    public String chooseExpert( Model model, @RequestParam("gameId") Long gameId) {
        String gameName = gameService.getGameById(gameId).getName();
        List<Coach> experts = coachService.getAllCoachesByGameId(gameId);

        model.addAttribute("gameId", gameId);
        model.addAttribute("experts", experts);
        model.addAttribute("gameName", gameName);

        return "experts.html";
    }

    @GetMapping("/reservations/form")
    public String showForm(Model model, @RequestParam("coachId") Long coachId) {
        Coach coach = coachService.getCoachNameById(coachId);
        model.addAttribute("coach", coach);
        return "form.html";
    }

我需要在第二个控制器中获取gameId,有什么方法吗?
重定向在这种情况下肯定没有帮助。有什么建议吗?

dxxyhpgq

dxxyhpgq1#

有几种方法可以实现它。
1.如注解中所述,您可以在showForm中将“gameId”参数作为@RequestParam传递:

@GetMapping("/reservations/form")
    public String showForm(Model model, @RequestParam("gameId") Long gameId, @RequestParam("coachId") Long coachId) {

1.你也可以把“gameId”放在session中,使它在第二个方法中可用:

@Controller
@SessionAttributes("gameId")
public class SomeController {

  @GetMapping("/reservations/chooseExpert")
  public String chooseExpert(Model model, @RequestParam("gameId") Long gameId) {
    String gameName = gameService.getGameById(gameId).getName();
    List<Coach> experts = coachService.getAllCoachesByGameId(gameId);

    model.addAttribute("gameId", gameId);
    model.addAttribute("experts", experts);
    model.addAttribute("gameName", gameName);

    return "experts.html";
  }

  @GetMapping("/reservations/form")
  public String showForm(Model model, @RequestParam("coachId") Long coachId, @ModelAttribute("gameId") String gameId) {
    ...
  }

}

相关问题