JSF 1.2 到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 JSF 2.x 中,尽可能推迟
HttpSession
的创建,以避免不必要的会话创建。仅当确实需要时才会创建它。在您调用它时,它显然尚未创建。将false
传递给getSession()
意味着容器不应该自动创建它(如果它不存在)。因此,如果它还不存在,它将返回null
。您需要将
true
传递给getSession()
。另请参阅:
ExternalContext #getSession(boolean)
javadoc与具体问题无关,这是代码味道。您到底需要 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. Passingfalse
togetSession()
means that the container shouldn't auto-create it if it doesn't exist. So if it doesn't exist yet, it will just returnnull
.You need to pass
true
togetSession()
instead.See also:
ExternalContext#getSession(boolean)
javadocUnrelated 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.