What happens to #SessionScoped #ManagedBean which is already in HttpSession? - jsf-2

Old code creates a #SessionScoped #ManagedBean (namely UserSession) at the first request in a ServletFilter and puts it in the HttpSession (if not already there).
Now what happens when some EL expression tries to access that ManagedBean the first time? I expected a second instance of UserSession (one created manually and one from JSF). So I instrumented the constructor, #PostConstruct and #PreDestroy with a few logging statements. Now it seems JSF never creates the UserSession - only the constructor is called.
Is this possible? Can JSF reuse that bean from HttpSession? Is it legit to put #SessionScoped beans in HttpSession?

Your observation is correct. Under JSF's covers, JSF itself also stores session scoped managed beans as an attribute of the HttpSession. So if it's already present, it will just be reused, regardless of the way how it has ended up in there.
Whether that's good or bad depends on the concrete functional requirement. Given your astonishment, I'd guess that it's bad and that you need to revise either the approach or the functional requirement. Perhaps you need a secondary (session scoped?) managed bean which injects the particular session attribute by #ManagedProperty.

Related

jsf2.1 - new ViewScoped bean being created [duplicate]

This doesn't seem right. I was doing some cleanup of my code and I just noticed this. Every ajax request is firing the constructor and #PostConstruct of my #ViewScoped bean. Even a simple database pagination is firing it.
I understood that #ViewScoped is longer than #RequestScoped and that it shouldn't be reconstructed on every request. Only after a complete page reload by GET.
In other words, your #ViewScoped bean behaves like a #RequestScoped bean. It's been recreated from scratch on every postback request. There are many possible causes for this, most of which boils down that the associated JSF view is not available anymore in the JSF state which in turn is by default associated with the HTTP session.
Provided that you can assure that the HTTP session itself is not the root cause of the problem, i.e. when #SessionScoped works absolutely fine, then walk through the below list of possible causes. Otherwise, if the HTTP session itself is also trashed and recreated on every single request, then you need to take a step back and look at session cookie and server configuration. Any cause related to a broken HTTP session is at least beyond the context of JSF.
You're using Mojarra 2.1.17 or older, and the view contains EL expressions which bind a view scoped bean property to a tag attribute which is evaluated during view build time. Examples are JSTL <c:if>, <c:forEach>, etc or JSF <ui:include>, <x:someComponent id="#{...}", <x:someComponent binding="#{...}">, etc. This is caused by a bug in Mojarra (issue 1496). See also Why does #PostConstruct callback fire every time even though bean is #ViewScoped? JSF
This is already fixed in Mojarra version 2.1.18. If you can't upgrade to a newer version, the workaround is to disable partial state saving as below in web.xml, see also JSTL in JSF2 Facelets... makes sense?
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>false</param-value>
</context-param>
Or when you want to target a specific set of JSF views only:
<context-param>
<param-name>javax.faces.FULL_STATE_SAVING_VIEW_IDS</param-name>
<param-value>/foo.xhtml;/bar.xhtml;/folder/baz.xhtml</param-value>
</context-param>
Important to mention is that binding the value of JSF component's id or binding attribute to a view scoped bean property is a bad practice. Those should really be bound to a request scoped bean property, or an alternative should be sought. See also How does the 'binding' attribute work in JSF? When and how should it be used?
You're using Mojarra 2.2.0, only that version has a (yet unknown) bug in maintaining the view scope which is already fixed in 2.2.1, see also issue 2916. Solution is to upgrade to a newer version.
The #ViewScoped annotation is imported from the wrong package. JSF offers two #ViewScoped annotations, one from javax.faces.bean package for JSF managed beans annotated with #ManagedBean, and another one from javax.faces.view package for CDI managed beans annotated with #Named. When the bean scope annotation does not match the bean management annotation, then the actual bean scope will become the bean management framework's default scope, which is #RequestScoped in JSF managed beans and #Dependent in CDI managed beans.
You need to ensure that you have either of the following constructs and don't mix them, see also #ViewScoped bean recreated on every postback request when using JSF 2.2.
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class CorrectJSFViewScopedBean implements Serializable {
import javax.inject.Named;
import javax.faces.view.ViewScoped;
#Named
#ViewScoped
public class CorrectCDIViewScopedBean implements Serializable {
The view is (accidentally?) marked transient via <f:view transient="true">. This basically turns on "stateless JSF", which is new since Mojarra 2.1.19. Hereby the JSF view simply won't be saved in the JSF state at all and logical consequence is that all referenced view scoped beans can't be associated with the JSF view anymore. See also What is the usefulness of statelessness in JSF?
The web application is configured with com.sun.faces.enableRestoreView11Compatibility context param set to true in an incorrect attempt to "avoid" ViewExpiredException. With this context param, the ViewExpiredException will never be thrown, but the view (and all associated view scoped beans) will just be recreated from scratch. However, if that happens on every request, then this approach actually hides another problem: the views expire way too soon. This indicates a possible problem in maintaining the JSF view states and/or the HTTP session. How to solve/configure that properly, head to javax.faces.application.ViewExpiredException: View could not be restored.
The web application's runtime classpath is polluted with multiple different versioned JSF API or impl related classes. This causes a corruption/mismatch in the identifiers/markers for the JSF view state. You need to make sure you don't have multiple JSF API JAR files in webapp's /WEB-INF/lib. In case you're using Maven, make carefully sure that you mark server-provided libraries as <scope>provided</scope>. See also "Installing JSF" section in our JSF wiki page and the answer to this related question: How to properly install and configure JSF libraries via Maven?.
When you're using PrimeFaces <p:dialog>, then make sure that the <p:dialog> has its own <h:form> and that it is not nested in another <h:form>. See also p:fileUpload inside p:dialog losing #ViewScoped values.
When you're combining PrimeFaces FileUploadFilter with PrettyFaces, then make sure that the FileUploadFilter also runs on PrettyFaces-rewritten/forwarded requests. See also ViewScoped bean rebuilt when FileUploadListener called using PrettyFaces and How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable.
When you're using PrettyFaces, a badly configured rewrite rule which redirects CSS/JS/image resources to a JSF page tied to a #ViewScoped bean will also give misleading behavior. See also CDI ViewScope & PrettyFaces: Multiple calls to #PostConstruct (JSF 2.2).

CDI Keeps all Injected tree references of SessionScoped beans?

I am starting a new project with JavaEE 7 and declared a Sessionscoped bean to maintain the web logged user information in session.
The UserSessionBean, as I named it, is intended to be lightweight - trying to avoid lots of data to be kept in the session by Weld. But in some cases I need to get all user information, so added a getUser() method which must query and retrieve a UserEntity from JPA. In order for the method to do its job, I need to #Inject other resources onto the UserSessionBean.
My question is: These dependant resources will be kept and serialised within the UserSessionBean by Weld until the context is destroyed?
The weld documentation says this:
An instance of a dependent bean is never shared between different
clients or different injection points. It is strictly a dependent
object of some other object. It is instantiated when the object it
belongs to is created, and destroyed when the object it belongs to is
destroyed.
That makes me think the all SessionBean tree is kept by weld during session life, but how can I keep a lightweight SessionBean and use injected CDI resources on it?
Since what you're injecting are also CDI beans, it is not the beans themselves that get serialised, but their lightweight proxies. Upon deserialisation, the proxies dynamically resolve the correct beans for whatever scope they are. See section 5.4 Client Proxies of the CDI1.0 spec. Hence, your bean is as lightweight as possible.

Why use a ShoppingCart as a Stateful Sesson Bean?

One typical example of using a Stateful Session Bean is through a ShoppingCart example. We create a bean instance of the ShoppingCart class, then store this instance within a HttpSession.
However, the same can be achieved easily with the ShoppingCart class being a normal Java class (or a stateless session bean). A request of adding a product comes in, we create a cart object, then put that cart object inside a HttpSession.
So, I don't see the point of using a stateful session bean ShoppingCart here. And in general, a stateful session bean doesn't seem to play any significant roles.
I would rephrase your question:
Why should I use mechanism for automatic session based bean management (maintaining one instance per session, persisting inside session) if I can implement it myself?
Yes, you can implement it yourself and it would be pretty simple. However you can just use Java EE mechanisms for that.

Setup an ObjectPool Bean with JSF-2

I want to create a JSF-2 Portlet with multiple SessionScoped Backing Beans. I'd also like them all to share some POJOs with a common SessionScoped Bean that will serve as an Object Pool.
I have two issues troubling me:
I'd like to have this bean Initialized before any of the Backing Beans. Note that no xhtml page will call an object directly to the Object Pool Bean, so at least one Backing Bean will be init before the ObjectPool. Is there some way to make sure it will be init first, except that calling in in PostConstruct of every other Backing Bean ?
I am confused on using ManagedProperties, because I need All the Backing beans to call the Object Pool's properties, while I also need the Backing Bean to call some Client / BackingBean functions. How can I do that without creating double references ?
For your first question you can use a f:prerenderView in your
login xhtml page. #SessionScoped beans are not created until you
reference them from the page or create them by yourself and store in
the context. If you link the f:prerenderView to some of your method
of the bean which acts like a pool it will be initialized for the
rest of the HttpSession. You can later inject it in your other
#SessionScoped beans using #ManagedProperty annotation.
About your second question, just remember you're not forced to go
through the view beans in order to obtain session properties. Haven't
you made the Object Pool itself a #ManagedBean? So access it
directly from your page!

Replacing a managed bean

Couple of questions on setting managed bean using CDI.
1. If a session bean is Injected into another using #Inject annotation, how to replace the entire session Bean?
2. In CDI, Is it possible to define Injection to only inject (not to outject).
If a session bean is Injected into another using #Inject annotation, how to replace the entire session Bean?
You don't. This requirement can mean only 1 thing: the session scope is the wrong scope for the bean in question. Perhaps you're looking for the conversation scope instead.
If you really need to, you can always add some clear() method which clears the state (thus, all of its properties) of the session scoped bean, but this is still fishy. Just choose the right scope from the beginning on.

Resources