Spring MVC:Flash属性与模型属性 [英] Spring MVC: flash attribute vs model attribute

查看:97
本文介绍了Spring MVC:Flash属性与模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

flash model 属性有什么区别?

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

I want to store an object and display it in my JSP as well as reuse it in other controller. I have use sessionAttribute and it works fine in the JSP, but the problem is when I try to retrieve that model attribute in other controller.

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

I lose some data. I searched around and found that flash attribute allows to past past value to different controller, doesn't it?

推荐答案

如果我们想通过attributes via redirect between two controllers,则不能使用request attributes(它们将无法通过重定向),也不能使用Spring的@SessionAttributes (由于Spring的处理方式),只能使用普通的HttpSession,这不是很方便.

If we want to pass the attributes via redirect between two controllers, we cannot use request attributes (they will not survive the redirect), and we cannot use Spring's @SessionAttributes (because of the way Spring handles it), only an ordinary HttpSession can be used, which is not very convenient.

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

Flash attributes provide a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting — for example, the Post/Redirect/Get pattern. Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and removed immediately.

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

Spring MVC has two main abstractions in support of flash attributes. FlashMap is used to hold flash attributes while FlashMapManager is used to store, retrieve, and manage FlashMap instances.

示例

@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方法进行检索.

In above example, request comes to handlePost, flashAttributes are added, and retrieved in handleGet method.

更多信息此处.

这篇关于Spring MVC:Flash属性与模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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