JSF 1.2 到 2.0 注释更改

发布于 2024-12-13 11:23:22 字数 367 浏览 2 评论 0原文

我从 1.2 迁移到 2.0,并使用注释将托管 bean 名称和范围从 faces-config.xml 移动到 bean。

一个 bean(sessionscoped) 有一个实例变量,它获取当前会话,如下所示: private HttpSession httpsess = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);

然后我在任何实例方法中调用 httpsess 变量以向会话添加内容。但是一旦我更改了注释。 httpsess 变量返回 null。当我将变量创建为局部变量时,它工作正常。为什么会出现这种情况呢?

I migrated from 1.2 to 2.0 and I moved my managed bean names and scopes from the faces-config.xml to the beans using annotations.

One bean(sessionscoped) has an instance variable which gets the current session as such:
private HttpSession httpsess = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);

And then I call the httpsess variable in any instance method to add stuff to the session. But once I made the annotation changes. The httpsess variable returns null. When I create the variable as a local variable it works fine. Why would this happen?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

另类 2024-12-20 11:23:22

在 JSF 2.x 中,尽可能推迟 HttpSession 的创建,以避免不必要的会话创建。仅当确实需要时才会创建它。在您调用它时,它显然尚未创建。将 false 传递给 getSession() 意味着容器不应该自动创建它(如果它不存在)。因此,如果它还不存在,它将返回null

您需要将 true 传递给 getSession()

HttpSession httpsess = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

另请参阅:


与具体问题无关,这是代码味道。您到底需要 HttpSession 来做什么?获取/设置一些属性?为什么不将其作为当前会话范围的托管 bean 的属性呢?无论如何,JSF 会话范围的托管 bean本身已经存储为会话属性。

In JSF 2.x, the creation of HttpSession is postponed as much as possible to avoid unnecessary session creation. It will only be created when it is really needed. It's apparently not been created yet at the point you're calling it. Passing false to getSession() means that the container shouldn't auto-create it if it doesn't exist. So if it doesn't exist yet, it will just return null.

You need to pass true to getSession() instead.

HttpSession httpsess = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

See also:


Unrelated to the concrete problem, this is a code smell. What exactly do you need the HttpSession for? To get/set some attributes? Why not just make it a property of the current session scoped managed bean? A JSF session scoped managed bean is by itself already stored as a session attribute anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文