CDI Bean recreated on every <h:inputtext>ajax call [duplicate] - ajax

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).

Related

Accessing to session objects from facelets

we are working on a customer platform project and we have some doubts about the session objects and the best way to access them.
In order, it may be:
Login from client
SessionScopped bean gets fired with the template render.
Diferent pages (facelets) with ViewScoped or RequestScoped bean to navigate to sections.
We are injecting the sessionscoped bean to the rest of the beans when needed, so we have the same properties everywhere.
The doubt is, in the diferent facelets of sections, how we should access to the session objects? i mean
#{requestscopedbean.sessionscopedbean.object}
or should be directly calling to the session bean like:
#{sessionscopedbean.object}
We use PrimeFaces 6.2, I guess it is not the point. Just in case. And we are running all this on a javaee-5 compatible server

No FacesContext found in JoinFaces ViewScope

We are currently migrating a rather big project from JavaEE (Wildfly) to Spring Boot 2.0.5 using JoinFaces 3.2.5 for JSF support. Unfortunately when starting the server we always get the following message:
Scope 'view' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No FacesContext found.
The problematic UI bean is a Spring Component additionally annotated with javax.faces.view.ViewScoped (like class StarterMBean in the joinfaces-maven-jar-example).
Is there anything special we have to be careful about, e.g. forbidden dependencies, special configurations etc?
We are thankful for every hint!
You have an singleton/application scoped bean which has a direct or indirect dependency on a view scoped bean. This forces the BeanFactory to construct the view scoped bean when the application starts, but view scoped beans can only be used in threads which are currently processing a JSF request.
There are multiple ways to solve this problem:
Try to model your beans to only have dependencies to beans with the same or a higher scope. (So application scoped beans can only use application scoped beans, view scoped beans can use view, session or application scoped ones and so on)
When you are 100% sure your application scoped bean will only use the view scoped one during the processing of a JSF request you can automatically or manually wrap the bean in a scoped proxy.
To get a scoped proxy automcatically, change #ViewScoped to #Scope(scopeName = "view", proxyMode = ScopedProxyMode.TARGET_CLASS)
If you have no access to the view scoped bean, you can declare the injection point as ObjectProvider<> in order to get a scoped proxy.
More information about this problem can be found here: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-scopes-other-injection

Ajax calls are not working when bean is changes to #Scope("request") with PrimeFaces

I am new to Spring/JSF.
I have a controller which is annotated by #Component which have a #Autowired class UserClass which has,
#Scope(value=org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE)
I need to create a new UserClass instance for each new request so my controller is annotated with #Scope("request") which works perfectly(Creating new instance for each request) with this annotation.
But it broke the ajax calls in <p:dataTable> selection, commondLink, <f:setPropertyActionListener...
NOTE : if I change the #Scope("request") to #ViewScoped the ajax works but my UserClass becomes singleton and all the data is shared between the threads.
I googled and got to know we need to either use JSF annotations or Spring but here I am using only Spring annotations.
And I found this, PrimeFaces doesn't work when bean scope is request but couldn't understand.
A component library like Primefaces heavily relies in a stateful model, which means using at least the view scope in your managed beans. If you use the request scope you'll be recreating the managed bean for every single request, including ajax requests, which I guess it isn't what you want (not the way to go with JSF, at least).
Your best is to use a custom Spring Scope in order to emulate the JSF view scope. I like this approach from the PF team (a bit old post, but still you can tune it for newer Spring versions) or this one, which is more elaborated.

How to set few parameter in the session of a jsf/primefaces application [duplicate]

I noticed that there are different bean scopes like:
#RequestScoped
#ViewScoped
#FlowScoped
#SessionScoped
#ApplicationScoped
What is the purpose of each? How do I choose a proper scope for my bean?
Introduction
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
#Request/View/Flow/Session/ApplicationScoped
A #RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A #ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A #FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A #SessionScoped bean lives as long as the established HTTP session. An #ApplicationScoped bean lives as long as the web application runs. Note that the CDI #Model is basically a stereotype for #Named #RequestScoped, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use #RequestScoped for simple and non-ajax forms/presentations. Use #ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use #FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use #SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use #ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an #ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a #SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a #RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a #ViewScoped bean for request, session or application scoped data, and abusing a #SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively #RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via #ManagedProperty in case of JSF managed beans or #Inject in case of CDI managed beans.
See also:
Difference between View and Request scope in managed beans
Advantages of using JSF Faces Flow instead of the normal navigation system
Communication in JSF2 - Managed bean scopes
#CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports #CustomScoped and #NoneScoped, which are rarely used in real world. The #CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.
The JSF #NoneScoped and CDI #Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a #NoneScoped or #Dependent is injected in a #SessionScoped, then it will live as long as the #SessionScoped bean.
See also:
Expire specific managed bean instance after time interval
what is none scope bean and when to use it?
What is the default Managed Bean Scope in a JSF 2 application?
Flash scope
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as #FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.
See also:
How to show faces message in the redirected page
Pass an object between #ViewScoped beans without using GET params
CDI missing #ViewScoped and #FlashScoped
Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using #ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.
From JSF 2.3 here are scopes that can be used on JSF Backing Beans:
1. #javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.
2. #javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.
3. #javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.
4. #javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
5. #javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.
6. #javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.
The following legacy answer applies JSF version before 2.3
As of JSF 2.x there are 4 Bean Scopes:
#SessionScoped
#RequestScoped
#ApplicationScoped
#ViewScoped
Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates
if the web application invokes the invalidate method on the
HttpSession object, or if it times out.
RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back
to the client. If you place a managed bean into request scope, a new
instance is created with each request. It is worth considering request
scope if you are concerned about the cost of session scope storage.
ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all
requests and all sessions. You place managed beans into the
application scope if a single bean should be shared among all
instances of a web application. The bean is constructed when it is
first requested by any user of the application, and it stays alive
until the web application is removed from the application server.
ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF
specification uses the term view for a JSF page.) As soon as the user
navigates to a different page, the bean goes out of scope.
Choose the scope you based on your requirement.
Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54]

Using OmniFaces 2.1 ViewScoped with Spring 3.1.0 in JSF 2.2

I'm trying to convert some pages to View scope (from Session Scope) to enable multiple browser tabs to support showing data from multiple entries from a datatable.
Does anyone know whether following the steps in this PrimeFaces blog Porting JSF 2.0′s ViewScope to Spring 3.0 will work to extend Spring to use org.omnifaces.cdi.ViewScoped from Omnifaces 2.1?
You can just use the approach described in the blog you found. Only you don't and can't exactly port in such way that it under the covers actually uses the specific #ViewScoped annotation. Basically, you should implement the same code as those annotations are under the covers using.
Both the standard JSF #ViewScoped and the OmniFaces #ViewScoped do under the covers basically the same as descibed in the blog: referencing the bean instances via UIViewRoot#getViewMap(). Only, the JSF 2.0/2.1 #ViewScoped didn't properly trigger #PreDestroy of beans in all cases. E.g. they won't be called when the underlying HTTP session expires. OmniFaces had solved those issues for JSF 2.0/2.1 users. JSF itself has solved them in 2.2. So in JSF 2.2 there is not really a reason to use OmniFaces #ViewScoped.
Although I'd like to hint here that I'm for future OmniFaces 2.2 planning to add a beforeunload hook to <o:form> when an OmniFaces #ViewScoped bean is used, so that the bean also really get destroyed when the user navigates away by GET, or refreshes the page, or closes the browser window, making it yet more useful again :)

Resources