Spring Boot redirectAttributes.addFlashAttribute不保留立即重定向中的值 [英] Spring boot redirectAttributes.addFlashAttribute not preserving the value in the immediate redirect

查看:31
本文介绍了Spring Boot redirectAttributes.addFlashAttribute不保留立即重定向中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现GET-POST-GET重定向模式的控制器类.我试图在POST请求中使用addFlashAttribute并将其重定向到GET,但是GET中的模型对象不包含设置值.这是我的代码:

I have a controller class which implements GET-POST-GET redirect pattern. I have tried to use addFlashAttribute in the POST request and redirecting to GET but the model object in GET does not contain the set value. Here is my code:

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

}

如果我在这里丢失了一些东西,请告诉我.

Please let me know, if I am missing something here.

推荐答案

在PRG情况下使用 RedirectAttributes 时,您要做的只是:

When using RedirectAttributes in a PRG situation, all you need to do is:

  1. RedirectAttributes 作为POST方法签名的参数
  2. 通过POST方法中的 addFlashAttribute 设置所需的属性
  3. 在GET方法签名中包含一个@ModelAttribute注释的参数,该参数引用了flash属性
  1. Include RedirectAttributes as parameter to the POST method signature
  2. Set the attribute you want via addFlashAttribute within the POST method
  3. Include a @ModelAttribute annotated parameter in the GET method signature which references the flash attribute

所以您真的不需要POST方法中的这一行:

So you really do not need this line from the POST method:

Map<String,?> m = redirectAttributes.getFlashAttributes(); // present here.

但是我认为您的实际问题是您无意中使用了以下行覆盖GET方法中的model属性:

modelMap.addAttribute("result", postResult); //postResult is empty

Flash属性已在重定向期间自动添加到模型中,因此上面的行实际上覆盖了它.如果您删除该行,它应该可以正常工作.

Flash attributes are already automatically added to the model during the redirection, so above line is actually overwriting it. If you remove that line it should work as intended.

这篇关于Spring Boot redirectAttributes.addFlashAttribute不保留立即重定向中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆