【问题标题】:Use of getFlashAttributes() in Spring's RedirectAttributes在 Spring 的 RedirectAttributes 中使用 getFlashAttributes()
【发布时间】:2014-01-02 07:33:49
【问题描述】:

为了在redirected方法中访问redirect属性,我们利用模型的map,如下所示:

@Controller
@RequestMapping("/foo")
public class FooController {

  @RequestMapping(value = "/bar", method = RequestMethod.GET)
  public ModelAndView handleGet(Model map) {
     String some = (String) map.asMap().get("some");
  }

  @RequestMapping(value = "/bar", method = RequestMethod.POST)
  public ModelAndView handlePost(RedirectAttributes redirectAttrs) {
    redirectAttrs.addFlashAttributes("some", "thing");
    return new ModelAndView().setViewName("redirect:/foo/bar");
  }

}

但是,为什么我们不能以这种方式访问​​它们:

      @RequestMapping(value = "/bar", method = RequestMethod.GET)
      public ModelAndView handleGet(RedirectAttributes redAttr) {
         String some = redAttr.getFlashAttributes().get("some");
      }

如果添加 flashAttributes 的唯一目的是它们在重定向方法中可供模型使用,那么 getFlashAttributes() 的目的是什么?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    RedirectAttributes 用于在重定向之前设置 flash 属性。它们在重定向后合并到 model 中,因此没有理由按照您的建议再次通过 RedirectAttributes 再次访问它们。


    能够像使用地图一样使用属性可能会很有用。你可以检查你设置了什么(containsKeyisEmpty,...)。然而,通配符泛型参数Map<String, ?> getFlashAttributes() 的使用会阻止写入映射,奇怪的是为什么他们使用它而不是普通的Object 参数。

    【讨论】:

    • 使用“redirectAttributes.addFlashAttribute”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多