ViewScoped bean extending another ViewScopedBean - jsf

I am using JSF 2.3.
Is it possible to have a ViewScoped bean extending another ViewScopedBean (using CDI or whatever)? In the xhtml template I would like to refer to any of both ViewScoped beans depending on some condition (i.e. user privileges)

Related

Getting data from JSF controller to EJB [duplicate]

Is is possible to inject JSF Managed Bean into an EJB? I have injected JSF Managed Beans in to another JSF Managed Bean as a #ManagedProperty. But when I do the same to the EJB, I get a null point exception.
No, that's not possible. The #ManagedProperty works inside #ManagedBean classes (JSF managed beans) only. You can only use #EJB or #Inject to inject another EJB or a CDI managed bean (a #Named class).
However, it makes design technically no sense to inject a front-end class like a JSF or CDI managed bean in a business service class like an EJB. An EJB should be designed in such way that it can without changes be reused together a completely different front-end like JAX-RS webservice or even a plain vanilla servlet. An EJB should absolutely not have any javax.faces.* imports/dependencies (like as that it should not have any javax.ws.rs.* nor javax.servlet.* ones).
If you intend to pass data from the JSF managed bean to an EJB, then just pass it as method argument. Such data is usually in flavor of a JPA #Entity or at least an ID/keyword which returns an entity.

JSF ViewScoped and SessionScoped bean destroyed after request [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 beans injection

Is this a correct approach to inject #ApplicationScoped bean in #SessionScoped bean? will this lead my application scoped bean to be stored in the session of every user?
I have an application scoped bean that contains some values we share among all the system users, and now I need to get that values within a method in a session bean.
Injecting a bean of the same or a broader scope in another bean is completely legal and correct either in JSF or CDI beans, like the example you provided.
The difference between CDI beans and JSF managed beans regarding that is when you try to inject a bean of a narrower scope in another bean (e.g inject #RequestScoped bean into #SessionScoped one), which is only possible as long as you are using CDI #Named beans, while not possible when working with JSF #ManagedBean.
The reason why this is possible for CDI beans is related to their Proxy Pattern mechanism, which is more flexible compared with the JSF mechanism (based on invoking the setters in order to directly inject a physical instance).
This proxy mechanism, allow the CDI container to pass a reference to a proxy instead of the injected bean (unless a bean has the default scope #Dependent). Therfore, that proxy will be responsbale of handling all calls to the injected bean and forward / redirect them to the correct bean instance.
See also:
CDI: Contexts and Dependency Injection for the Java EE platform - Client proxies
Java EE 6 #javax.annotation.ManagedBean vs. #javax.inject.Named vs. #javax.faces.ManagedBean
Backing beans (#ManagedBean) or CDI Beans (#Named)?
ManagedProperty in CDI #Named bean returns null

Injecting JSF Managed Bean to a EJB

Is is possible to inject JSF Managed Bean into an EJB? I have injected JSF Managed Beans in to another JSF Managed Bean as a #ManagedProperty. But when I do the same to the EJB, I get a null point exception.
No, that's not possible. The #ManagedProperty works inside #ManagedBean classes (JSF managed beans) only. You can only use #EJB or #Inject to inject another EJB or a CDI managed bean (a #Named class).
However, it makes design technically no sense to inject a front-end class like a JSF or CDI managed bean in a business service class like an EJB. An EJB should be designed in such way that it can without changes be reused together a completely different front-end like JAX-RS webservice or even a plain vanilla servlet. An EJB should absolutely not have any javax.faces.* imports/dependencies (like as that it should not have any javax.ws.rs.* nor javax.servlet.* ones).
If you intend to pass data from the JSF managed bean to an EJB, then just pass it as method argument. Such data is usually in flavor of a JPA #Entity or at least an ID/keyword which returns an entity.

Difference between managed bean and backing bean

I came across the terms "managed bean" and "backing bean" in several forums. Many people think both are the same. But, there seems to be a slight difference. Can any one help me to understand the exact difference between these two terms?
Changing my initial answer - there is no meaningful difference between the two. The tutorial says that backing beans are later declared as managed beans. So, to summarize:
a backing bean is the class out of context
a managed bean is the backing bean whenever it is declared to be used with the JSF managed bean facility.
I've never actually used the term "backing bean", because I found no use to it. So you might be better off using only "managed bean". Note that in JSF 2.0 (and in CDI) you have #ManagedBean- so your bean is a managed bean.
BalusC suggested that "backing bean" is the definition, and "managed bean" is the instance. While this might have been the original idea of JSF creators, I don't think it is worth supporting it. CDI and spring for example don't have different term for "bean definition" and "bean instance".
The JSF 2.0 specification mentions the term "backing bean" only a few times, with no definition whatsoever. In addition to that it mentions "backing bean class", which might mean that "backing bean" != "backing bean class", which brings further confusion.
So to conclude - for me both are interchangeable, and I'd stick to only using "managed bean"
What is Managed Bean?
JavaBean objects managed by a JSF implementation are called managed beans.
A managed bean describes how a bean is created and managed.
It has nothing to do with the bean's functionalities.
What is Backing Bean?
Backing beans are JavaBeans components associated with UI components used in a page.
Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data.
The backing bean defines properties and handling-logics associated with the UI components used on the page.
Each backing-bean property is bound to either a component instance or its value.
Backing bean also defines a set of methods that perform functions for the component, such as validating the component's data, handling events that the component fires and performing processing associated with navigation when the component activates.
What are the differences between a Backing Bean and Managed Bean?
Backing Beans are merely a convention, a subtype of JSF Managed Beans which have a very particular purpose. There is nothing special in a Backing Bean that makes it different from any other managed bean apart from its usage.
MB : Managed Bean ; BB : Backing Bean
1) BB: A backing bean is any bean that is referenced by a form.
MB: A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed.
The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml.
2) BB: Backing Beans should be defined only in the request scope
MB: The managed beans that are created by JSF can be stored within the request, session, or application scopes .
Backing Beans should be defined in the request scope, exist in a one-to-one relationship with a particular page and hold all of the page specific event handling code.
In a real-world scenario, several pages may need to share the same backing bean behind the scenes.
A backing bean not only contains view data, but also behavior related to that data.
Backing Bean is any bean that is bound with JSF UI. while Managed bean is any bean
Simply put,
You as developer do:
#ManagedBean(name="managedBean")
#RequestScoped
public class BackingBean {
// ...
}
JSF as bean management framework does under the covers:
BackingBean managedBean = new BackingBean();
externalContext.getRequestMap().put("managedBean", managedBean);
So, the backing bean is the concrete class which is developed by you and usually tied to the view, and the managed bean is the concrete instance, which is under the covers created and put in the desired scope by the bean management framework on demand, and available by #{managedBean} in EL. You never need to create and put it in the scope yourself. If you did so then there's no means of a framework-managed bean.
CDI #Named and Spring #Component do essentially the same thing as JSF #ManagedBean.
To learn more about how bean management frameworks like JSF, CDI and Spring find and create their managed beans, the following troubleshooter should provide in depth insight: Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable.
See also:
What components are MVC in JSF MVC framework?
JSF Controller, Service and DAO
JSF managed bean naming conventions
http://docs.oracle.com/javaee/5/tutorial/doc/bnaqm.html says
A typical JavaServer Faces application includes one or more backing beans, each of which is a JavaServer Faces managed bean that is associated with the UI components used in a particular page. Managed beans are JavaBeans components (see JavaBeans Components) that you can configure using the managed bean facility, which is described in Configuring Beans. This section introduces the basic concepts on creating, configuring, and using backing beans in an application.
http://docs.oracle.com/javaee/6/tutorial/doc/bnaqm.html makes no mention of "backing bean".
Managed Beans are managed (instantiated and destroyed) by container.
Backing Beans are managed beans that back views as data models.
I would say that the backing bean is a bean used strictly for UI purposes, that is, referenced in the jsp files. After all, all beans managed by JSF container are managed beans, however there are different contexts in which they might be used. For more see accepted answer here: JSF : ManagedBean, Good place to deal with Business Logic?
Backing Bean is a kind of Managed Bean. Managed Bean is an Object (i.e. instance of a Class ), created by a container (that's why it is called managed) and of course that Object has a Class and if you feel like it, you can create as many instances of that class no matter what annotation they have with m = new MyManagedBean(), just it will be a Not-So-Managed-Bean or at least not managed by a container but managed by you :)
And backing bean is a kind of managed bean (as Santosh put it: a convention) that usually uses the JSF requestScope (but in some frameworks like ADF there is even a designated scope only for backing beans called backingBeanScope - you would have never guessed) .
And yes... The flavor of jsf managed beans that one would call BackingBeans is used to bind UIComponents and write ActionListeners, while lets say "model beans" flavor would go in the session scope for example and hold your data
I took a very good (expensive) course on JSF. What I learned there is just about what is explained in http://www.avromroyfaderman.com/2008/07/from-backing-bean-to-managed-bean/.
Perhaps this difference is not the theoretical difference or the etymology of the terms, but it is certainly a very practical way to set up your architecture, especially if you are part of a large project with multiple developers and/or need to maintain a lot of code for a long time. Basically the idea is that you put your UI Business Logic in Managed Beans. Backing beans are sparse and just support the page itself.
From this link JSF - Managed Beans
Managed Bean :
Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a java bean managed by JSF framework.
From this link Creating and Using a Backing Bean for a Web Page :
Backing Bean :
In JSF, backing beans are JavaBeans used mainly to provide UI logic and to manage data between the web tier and the business tier of the application (similar to a data transfer object). Typically you have one backing bean per JSF page. The backing bean contains the logic and properties for the UI components used on the page.
NB:
For a backing bean to be available when the application starts, you
register it as a managed bean with a name and scope
Managed Bean:
A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) or using Annotations. Managed Bean automatically created (and optionally initialized) by JSF when it is needed.
If you use Managed Bean in your application you have to use following syntax in JSF page to set or get values form bean
<h:inputText value="#{user.name}"/>
Backing Bean:
A bean that contains some or all component objects of a web form. Such a bean is called a backing bean for the web form.
When you use a backing bean, you need to wire up the components on the
form to those on the bean. You use the binding attribute for this purpose
Example:
<h:inputText binding="#{myForm.myComponent}" .../>
Observe how we are getting or setting values to Backing bean.
Backing Beans should be defined in the request scope, exist in a one-to-one relationship with a particular page and hold all of the page specific event handling code
Hope it useful to someone.

Resources