sotn
sotn

Reputation: 2101

JSF 1.2 to 2.0 annotation change

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?

Upvotes: 1

Views: 323

Answers (1)

BalusC
BalusC

Reputation: 1108722

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.

Upvotes: 0

Related Questions