无法读取控制器中RedirectAttribute发送的参数

时间:2017-08-15 16:05:28

标签: java spring spring-mvc

我有/的控制器和另一个用于提交表单的控制器,我希望在表单提交后重定向到/控制器,并显示已成功注册的消息。

这是/的控制器:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String mainPage(@RequestParam(value = "registerSuccessful", required = false) boolean registerSuccessful,
                       ModelMap modelMap) throws UnknownHostException {
    boolean isDeviceRegistered = mainService.isDeviceRegistered();
    modelMap.addAttribute("isDeviceRegistered", isDeviceRegistered);
    modelMap.addAttribute("registerSuccessful", registerSuccessful);
    return "main";
}

/registerForm的控制器:

@RequestMapping(value = "registerForm", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public String saveDeviceInfo(@ModelAttribute("deviceInfo") DeviceInfo deviceInfo,
                             RedirectAttributes redirectAttributes,
                             BindingResult result, ModelMap modelMap){
    mainService.saveDeviceInfo(deviceInfo);
    redirectAttributes.addFlashAttribute("registerSuccessful", true);
    return "redirect:/";
}

如您所见,我发送了true属性registerSuccessful但是当我在重定向后阅读registerSuccessful处理程序上/的内容时,它是错误的。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

像这样使用@ModelAttribute

@RequestMapping(value = "/", method = RequestMethod.GET)
public String mainPage(@ModelAttribute(value = "registerSuccessful") boolean registerSuccessful,
                       ModelMap modelMap) throws UnknownHostException {
    boolean isDeviceRegistered = mainService.isDeviceRegistered();
    modelMap.addAttribute("isDeviceRegistered", isDeviceRegistered);
    modelMap.addAttribute("registerSuccessful", registerSuccessful);
    return "main";
}