gpt4 book ai didi

java - 为什么 SessionAttributes 在 GET 重定向时被清除?

转载 作者:搜寻专家 更新时间:2023-10-31 19:56:07 25 4
gpt4 key购买 nike

为简单起见,这些代码片段将被缩短。这样做的目的是获取一个 GET 参数,在 session 中设置它,然后重定向回 GET 并删除 url 参数。基本上,URI 清理。如果有更好/更简单的方法来做到这一点,我会很高兴听到。

我有一个这样定义的 Controller :

@Controller
@RequestMapping("/path/page.xhtml")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@SessionAttributes({ "myParam1", "myParam2" })
public class MyController {

@RequestMapping(method = RequestMethod.GET, params = { "urlParam2" })
public String handleUriParam(@RequestParam(value = "urlParam2", required = false)
final Long urlParam2,
final RedirectAttributes redirs) {
// at this point, myParam1 is set on the session.
// now set the param as a flash attrib with the name of the session variable
redirs.addFlashAttribute("myParam2", urlParam2);
return "redirect:/path/page.xhtml";
}

@RequestMapping(method = RequestMethod.GET, params = {})
public String doGetStuff(ModelMap model) {
// do stuff using myParam1 and myParam2.
// problem is, myParam2 is on the session, but myParam1 is not!
}

}

就像代码所说的那样,当重定向发生时,不知何故 myParam1 被取消设置。我可以通过将 ModelMap 传递给 handleUrlParam 方法并手动将 myParam1 添加到 flash 属性来解决这个问题,但这似乎违背了目的我的想法。

为什么 SessionAttribute myParam1 在重定向后被删除?

有没有更好的方法从 URI 中提取参数并将它们放在 session 中?

更新

因此,无论何时使用 RedirectAttributes,您都必须确保将要携带的任何 SessionAttribute 放入 FlashAttributes 的重定向中,否则它们会迷路。我想这是因为 SessionAttribute 被拉离了 ModelMap(使用时被 FlashAttributes 取代)。这是 Spring 中的错误还是故意行为?如果是故意的,有人可以解释为什么吗?我认为 SessionAttribute 应该一直存在,直到 session 结束后被移除。

Similar StackOverflow post here .

附录

鉴于所提供的已接受答案,我仍然对如何在将 URI 参数置于用户 session 中时清除它们感到困惑。我考虑过的一个选择是为我试图存储的半原始对象(java.lang.Integer、java.lang.String)创建一个包装器,因为它们不会被放置在 URI 字符串上,但这似乎很老套我。如果有人有更好的方法来接受 GET 参数,将它们存储在用户的 session 中,并从用户的地址栏中清除这些参数(这将需要重定向),我将很乐意使用它。

最佳答案

所以我四处查看代码和 Internet 以找出它不起作用的原因。

Spring 有两个完全独立的模型映射 - 一个用于标准 View 渲染,另一个在发出重定向时使用。这可以在 ModelAndViewContainer 中观察到.

现在 session 属性持久化完成了based on the result from mavContainer#getModel() .对于重定向场景,这将返回重定向模型。因此,您在标准 Model/ModelMap 上设置的任何内容都会丢失。

在谈论标准模型属性时,这是有道理的。模型主要用于将对象传递给 View 。使用重定向时,您正在处理完全不同的情况。您希望通过 HTTP 重定向传输对象 - 因此采用了分离的基于字符串和 flash 的模型。

但是我的感觉是他们在 designing this feature 时忘记了 session 属性.有一些不错discussion in Spring's Jira ,但是它们都没有解决这个具体问题。

所以是的...这可能是 Spring 的 Jira 的主题。可能被归类为错误,因为这会阻止任何人在使用时设置 session 模型属性重定向。通过 RedirectAttributes#addFlashAttribute 强制 Spring 存储您的 session 属性在我看来是一种 hack,并且本身就是一种错误

关于java - 为什么 SessionAttributes 在 GET 重定向时被清除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17086216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com