flash属性与模型属性

时间:2014-09-01 03:56:15

标签: spring-mvc attributes

flash和model属性有什么不同?

我想存储一个对象并将其显示在我的jsp中,并在其他控制器中重用它。我使用sessionAttribute并且它在jsp中工作正常,但问题是当我尝试在其他控制器中检索model属性时。

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

1 个答案:

答案 0 :(得分:7)

如果我们想要传递attributes via redirect between two controllers,我们就不能使用request attributes(它们将无法在重定向中存活),我们也无法使用Spring的@SessionAttributes(因为Spring处理它的方式) ),只能使用普通的HttpSession,这不太方便。

Flash属性为一个请求提供了一种存储打算在另一个请求中使用的属性的方法。重定向时最常需要这种方法 - 例如,Post / Redirect / Get模式。 Flash重定向(通常在会话中)之前临时保存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