本文介绍了Spring RedirectAttributes:addAttribute() 与 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 类有两个方法:

阅读 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 中(在用户 session 内部维护并删除一旦下一个重定向的请求得到满足)

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

addAttribute() 本质上构造了请求参数您的属性并根据请求重定向到所需的页面参数.

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

所以 addFlashAttribute()优势是你可以在你的 flash 属性中存储几乎任何对象(因为它不是序列化为请求参数,但作为对象维护),而使用 addAttribute() 因为您添加的对象被转换为普通请求参数,所以您非常限于像 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() 与 addFlashAttribute()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:01