Spring MVC:flash属性vs model属性



flashmodel属性之间有什么不同?

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

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

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

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

Spring MVC有两个主要的抽象来支持flash属性。FlashMap用于保存闪存属性,而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");
  }
}

在上面的例子中,请求到达handlePost,添加flashAttributes,并在handleGet方法中检索。

更多信息请点击此处。

最新更新