![](/img/trans.png)
[英]Keep object in the view after refreshing when using RedirectAttributes.addFlashAttribute
[英]Spring boot redirectAttributes.addFlashAttribute not preserving the value in the immediate redirect
我有一個控制器類,它實現了 GET-POST-GET 重定向模式。 我嘗試在 POST 請求中使用 addFlashAttribute 並重定向到 GET 但 GET 中的模型對象不包含設置值。 這是我的代碼:
@Controller
@RequestMapping("/eg")
public class Example extends AbstractBaseController {
@RequestMapping(value = "/account", method = RequestMethod.GET)
public String renderFavouriteView(
HttpServletRequest request,
HttpServletResponse response,
ExtendedModelMap modelMap,
@ModelAttribute("result") String postResult) {
modelMap.addAttribute("result", postResult); //postResult is empty
return "account.ftl";
}
@RequestMapping(value = "/account", method = RequestMethod.POST)
public String handleFavouriteView(
AccountForm accountForm,
HttpServletRequest request,
HttpServletResponse response,
ExtendedModelMap modelMap,
RedirectAttributes redirectAttributes) {
ServiceResult serviceResult = myAccountService.createAccount(accountForm);
if (!serviceResult.isSuccess()) {
redirectAttributes.addFlashAttribute("result", "Done");
} else {
redirectAttributes.addFlashAttribute("result", "Failed");
}
Map<String,?> m = redirectAttributes.getFlashAttributes(); // present here.
return "redirect:/eg/account";
}
}
如果我在這里遺漏了什么,請告訴我。
在 PRG 情況下使用RedirectAttributes
時,您需要做的就是:
RedirectAttributes
作為參數包含在 POST 方法簽名中addFlashAttribute
設置您想要的屬性所以你真的不需要 POST 方法中的這一行:
Map<String,?> m = redirectAttributes.getFlashAttributes(); // present here.
但我認為您的實際問題是您無意中用以下行覆蓋了 GET 方法中的模型屬性:
modelMap.addAttribute("result", postResult); //postResult is empty
Flash 屬性在重定向期間已經自動添加到模型中,因此上面的行實際上是覆蓋它。 如果您刪除該行,它應該按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.