Spring RedirectAttributes:addAttribute()vs addFlashAttribute() [英] Spring RedirectAttributes: addAttribute() vs addFlashAttribute()

查看:980
本文介绍了Spring RedirectAttributes:addAttribute()vs addFlashAttribute()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我的理解是在我们的控制器请求映射方法中,我们可以指定 RedirectAttributes 参数,并在请求被重定向时使用属性填充它。

My understanding so far is on our controller request mapping method we can specify RedirectAttributes parameter and populate it with attributes for when the request gets redirected.

示例

@RequestMapping(value="/hello", method=GET)
public String hello(RedirectAttributes redirAttr)
{
   // should I use redirAttr.addAttribute() or redirAttr.addFlashAttribute() here ?

   // ...

   return "redirect:/somewhere";
}

重定向属性将在重定向到的目标页面上可用。

The redirect attributes will then be available on the target page where it redirects to.

RedirectAttributes 类有两种方法:

  • addAttribute()
  • addFlashAttribute()

已阅读Spring文档一段时间但我有点迷茫。这两者之间的基本差异是什么?我应该如何选择使用哪一个?

Have been reading Spring documentation for a while but I'm a bit lost. What is the fundamental difference between those two, and how should I choose which one to use?

推荐答案

这是差异


  • addFlashAttribute()实际上将属性存储在 flashmap
    (内部维护在用户会话中并删除
    一旦下一个重定向请求得到满足)

  • addFlashAttribute() actually stores the attributes in a flashmap (which is internally maintained in the users session and removed once the next redirected request gets fulfilled)

addAttribute()本质上构造请求参数超出
您的属性并使用请求
参数重定向到所需页面。

addAttribute() essentially constructs request parameters out of your attributes and redirects to the desired page with the request parameters.

addFlashAttribute()优势将是您可以在 flash属性中存储几乎任何对象(因为它根本没有序列化为请求参数,而是作为对象维护),而使用 addAttribute(),因为您添加的对象获得了tran对于一个普通的请求参数,您只能使用 String 或基元等对象类型。

So the advantage of addFlashAttribute() will be that you can store pretty much any object in your flash attribute (as it is not serialized into request params at all, but maintained as an object), whereas with addAttribute() since the object that you add gets transformed to a normal request param, you are pretty limited to the object types like String or primitives.

这篇关于Spring RedirectAttributes:addAttribute()vs addFlashAttribute()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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