gpt4 book ai didi

java - Spring生命周期问题: the annotation @SessionAttributes makes session attributes live longer than the session itself

转载 作者:行者123 更新时间:2023-12-01 14:22:45 26 4
gpt4 key购买 nike

这是可以重现此问题的代码:

@Controller
public class FirstController {
@RequestMapping(value = "firstpage", method = GET)
public String myHander(HttpSession httpSession) {
if (httpSession.getAttribute("someClass") == null) {
httpSession.setAttribute("someClass", new SomeClass());
}
return "firstpage";
}
}

第一个 Controller 会将某些内容放入 session 中(如果 session 中尚不存在)。

@Controller
@SessionAttributes(types = SomeClass.class)
public class SecondController {

@RequestMapping(value = "secondpage", method = GET)
public String myHandler(SomeClass someClass, HttpSession httpSession) {
//asking spring for the SomeClass parameter, that's why we put it in the annotation.
System.out.print(someClass.hashCode());

httpSession.invalidate();

return "secondpage";
}
}

第二个 Controller 终止 session 。

在两个jsp文件中,我有以下代码打印 session 对象的哈希码和 session 属性的哈希码:

session hash:
<%= session.hashCode() %>
<br/>
someclass hash:
<%= session.getAttribute("someClass").hashCode() %>

现在,如果我运行应用程序并访问“firstpage”,我会得到:

session hash: 1838367636

someclass hash: 1075505853

然后我访问“第二页”,并会得到这个:

session hash: 842656294

someclass hash: 1075505853

我们可以看到 session 本身发生了变化,因为第二个 Controller 杀死了 session 。但 session 属性(SomeClass 类型)保持不变。

然后,如果我尝试重新访问“第二页”, session 对象每次都会更改,但 session 属性保持不变。

为什么 session 属性(应该附加到 session )的生命周期比 session 本身更长?

PS:完整代码在这里:https://github.com/cuipengfei/One-hundred-thousand-why/tree/master/20130701SessionAttributesLifeCycle/SpringMVC

您可以使用 mvn jetty:run 运行它来重现该问题。

最佳答案

documentation对于这个注释不是特别清楚,但我的理解是它用于在同一 Controller 中的方法之间共享值。当我读到以下内容时:

This will typically list the names of model attributes or types of model attributes which should be transparently stored in the session or some conversational storage, serving as form-backing beans between subsequent requests

我将其解释为意味着每个 Controller 方法调用都将通过调用来包装:(1) 在进入之前加载 session 属性,以及 (2) 在退出时存储它们。这将具有您所看到的行为。

注释的 javadoc 中的以下内容强化了这一点(imo):

For permanent session attributes, e.g. a user authentication object, use the traditional session.setAttribute method instead

如果他们告诉您使用标准函数来修改 session ,这对我来说意味着注释不仅仅是访问 session 中项目的一种方式。

最后一个数据点:如果这个注释管理 session 数据的方式,为什么要有 session 范围的 bean?

关于java - Spring生命周期问题: the annotation @SessionAttributes makes session attributes live longer than the session itself,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407052/

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