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

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

问题描述

flashmodel属性有什么区别?

我想存储一个对象并将其显示在我的 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?

推荐答案

如果我们想在两个控制器之间通过重定向传递属性,我们不能使用请求属性 (他们将无法在重定向中存活),并且我们不能使用 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天全站免登陆