【问题标题】:Spring MVC: flash attribute vs model attributeSpring MVC:flash 属性与模型属性
【发布时间】:2014-09-01 03:56:14
【问题描述】:

flashmodel属性有什么区别?

我想存储一个对象并将其显示在我的 JSP 中,并在其他控制器中重用它。我使用了sessionAttribute,它在JSP 中运行良好,但问题是当我尝试在其他控制器中检索model 属性时。

我丢失了一些数据。我四处搜索,发现flash attribute 允许将过去的值传递给不同的控制器,不是吗?

【问题讨论】:

    标签: spring-mvc attributes


    【解决方案1】:

    如果我们想通过attributes via redirect between two controllers,我们不能使用request attributes(它们将无法在重定向中存活),我们也不能使用Spring的@SessionAttributes(因为Spring处理它的方式),只能使用普通的@ 987654327@可以用,不是很方便。

    Flash 属性 为一个请求提供了一种方法来存储打算在另一个请求中使用的属性。这在重定向时最常需要——例如,Post/Redirect/Get 模式。 Flash 属性在重定向之前(通常在会话中)临时保存,以便在重定向之后对请求可用并立即删除。

    Spring MVC 有两个主要的抽象来支持 Flash 属性。 FlashMap 用于保存 flash 属性,FlashMapManager 用于存储、检索和管理 FlashMap 实例。

    示例

    @Controller
    @RequestMapping("/foo")
    public class FooController {
    
      @RequestMapping(value = "/bar", method = RequestMethod.GET)
      public ModelAndView handleGet(Model model) {
        String some = (String) model.asMap().get("some");
        // do the job
      }
    
      @RequestMapping(value = "/bar", method = RequestMethod.POST)
        public ModelAndView handlePost(RedirectAttributes redirectAttrs) {
        redirectAttrs.addFlashAttribute("some", "thing");
    
        return new ModelAndView().setViewName("redirect:/foo/bar");
      }
    
    }
    

    在上面的例子中,请求来到handlePostflashAttributes被添加,并在handleGet方法中检索。

    更多信息herehere

    【讨论】:

    • 我使用几乎相同的代码,但由于某种原因,我的模型没有填充 flashAttributes。这是我的问题*.com/questions/59465326/…
    • "我们不能使用 Spring 的 @SessionAttributes (因为 Spring 处理它的方式)" -- 请您扩展这部分,尤其是括号内的部分?