ManagedBean Params not accepted and Bean seemingly not in scope - jsf-2

This uses the same code that comes from
primefaces tree control
#ManagedBean( name = "theName", eager = true)
The first question is why "name" and "eager" are not recognised. Eclipse suggests I change either parameter to "value" - so not sure whats going on there.
Then, where I have been careful to capitalise where necessary and create my bean
public class TreeBean implements Serializable {
and reference it in my xhtml
<h:form id="mainForm">
<p:tree id="treeSingle" value="#{treeBean.root}" var="node"
selectionMode="single"
selection="#{treeBean.selectedNode}">
(paying attention to the capitalisation of the classname).
The output shows only a narrow bar. System.out.println("Constructor called") suggests the bean is not known. To support this, if I press the button as coded in the example (link provided at the top) I get the error
Jan 13, 2014 12:19:26 AM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: javax.el.PropertyNotFoundException: /HelloWorld.xhtml #23,50 selection="#{treeBean.selectedNode}": Target Unreachable, identifier 'treeBean' resolved to null
at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:133)
I've run out of ideas now as to what could be the problem. Is there any way of further debugging this or anyone got any ideas about the eager/name thing and what is causing the Bean class to be (I assume) not to be seen.
Thanks in advance.
Kevin

beans should be defined this way:
#ManagedBean(name="treeBean")
#SessionScoped // or whatever scope you would like to use
public class TreeBean implements Serializable {
....
Usage in XHTML: ...="#{treeBean.root}"
Or
#ManagedBean(name="xyz")
#SessionScoped // or whatever scope you would like to use
public class TreeBean implements Serializable {
....
Usage in XHTML: ...="#{xyz.root}"
bean name is just a key for the map, you can name it whatever you want
the scope of the bean should be from the package javax.faces.bean
i.e. for sessionscoped beans you have to import
import javax.faces.bean.SessionScoped;
and for the managedBean Annotation
import javax.faces.bean.ManagedBean;

Here you can find different ways to define a JSF managed bean and also here you can find a really good discuss about managed beans.

Related

Call session scoped bean method on every view

Perhaps this is a question I should be able to find documentation on, but I'm unfamiliar with a lot of the jargon so I'm struggling.
Basically, I'm using JSF2. I have a SessionScoped bean, and it uses a postconstruct init() method. I want the init() method to be called everytime the session starts, which works fine, but I also want it to be called every time the view loads.
Is there an easy way to do this?
Thanks!
Replace #PostConstruct by <f:event type="preRenderView">.
<f:event type="preRenderView" listener="#{sessionScopedBean.init}" />
Better, however, is to split it into 2 beans: a #SessionScoped one and a #ViewScoped one. Then just reference the #ViewScoped one in the view instead and inject the #SessionScoped one as a property of the #ViewScoped one.
#Named
#ViewScoped
public class ViewScopedBean {
#Inject
private SessionScopedBean sessionScopedBean;
#PostConstruct
public void init() {
// ...
}
// ...
}
See also:
When to use f:viewAction / preRenderView versus PostConstruct?
How to choose the right bean scope?

jsf 2 Session bean created for every request [duplicate]

This question already has an answer here:
#SessionScoped bean looses scope and gets recreated all the time, fields become null
(1 answer)
Closed 6 years ago.
ello
I have 2 Managed beans, one View scoped, the other Session scoped. The View scoped bean is defined as
#ManagedBean
#ViewScoped
public class InvoiceController implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty(value="#{invoiceService}")
private InvoiceService invoiceService;
The session scoped bean as
#ManagedBean
#SessionScoped
public class InvoiceService implements Serializable{
I am using the session scoped bean to hold a flag used to decide if a panel should be rendered, when I run this through the debug I find that every time I call the method on the sesison bean, it is a new instance of the bean and therefore does not retain the value of my flag between requests.
What am I doing wrong?
That can happen if you have imported #SessionScoped from the javax.enterprise.context package instead of from the javax.faces.bean package. The former works on CDI #Named beans only, while the latter works on JSF #ManagedBean beans only.
A JSF #ManagedBean without any valid scope would default to #NoneScoped which means that it's newly constructed on every single EL expression referencing the bean, such as the #ManagedProperty. This explains the symptoms you're seeing.
I had a similar problem. I use a save-method in the view scoped bean that calls a method in the session scoped bean to update some values.
This is what I found out by debugging (excuse my non-Java-guru English):
When first loading the page, the instance number of the injected session bean was for example 111111.
But in the save-method (and all other methods called by an action like a commandButton or action listeners btw), suddenly the session bean was of another instance (say 222222).
Both instances 111111 and 222222 contained the very same values.
All methods I called now were done in the 222222 instance and it changed values in there as I wanted it. But the 111111 instance remained untouched and unchanged.
So 222222 was basically a deep(?) clone of 111111, and not even a copy.
But, after the save-method was done and the page got reloaded, the original 111111 instance was used again in the view scope bean.
The 222222 instance just got thrown to the garbage.
My solution for this problem:
I'm not using the ManagedProperty injection anymore.
Instead I made some helper code to get the session bean wherever I need it (aka in the view scoped bean methods):
public Object getSessionBean(String sessionBeanName)
{
return FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(FacesContext.getCurrentInstance().getELContext(), null, sessionBeanName);
}
For your example above, the call would be:
InvoiceService invoiceService = (InvoiceService) helper.getSessionBean("invoiceService");
Call it in your methods, do not store it as a field in the view scoped bean.
I hope this somehow helps you fix your problem.

How can I retrieve an object on #WindowScoped?

In this post Dynamic ui:include I asked how I could store an object in some state that could permit me to load a new windows, or tab, of the same browser and it was not stored also in the new windows. Adrian Mitev told me to use #WindowScoped, an option of MyFaces extension called CODI and i tried to implement it.
Now I should say that I'm blind and when I tried to open Apache Wiki my browser crashes on many pages so I can't read the guides.
However I add the source code on my project and the compiler didn't give any errors.
The problem is that now thepage when I try to retrive the bean that I stored by #WindowScoped doesn't work properly!
I use this code in my bean:
#ManagedBean (name="logicBean" )
#WindowScoped
In include.xhtml I retrieve the parameter with this code:
<ui:include src="#{logicBean.pageIncluded}"/>
And in my other beans I retrieve the LogicBean with this code (and I'm sure that the problem is on this code)
LogicBean l = (LogicBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("logicBean");
How can I retrive the "correct" LogicBean object?
You're trying to get the LoginBean from the session map. This works only for session scoped beans with the standard JSF #SessionScoped annotation.
The canonical way to access other beans is using #ManagedProperty on the retrieving bean.
E.g.
#ManagedBean
#RequestScoped
public class OtherBean {
#ManagedProperty("#{logicBean}")
private LogicBean logicBean;
// Getter+Setter.
}
If you really need to access it inside the method block by evaluating the EL programmatically, you should be using Application#evaluateExpressionGet() instead:
FacesContext context = FacesContext.getCurrentInstance();
LogicBean logicBean = context.getApplication().evaluateExpressionGet(context, "#{logicBean}", LogicBean.class);
// ...

what to use, managed beans (backing beans) or entity beans?

I see a lot of examples marking beans as entity beans (#Entity) & named beans (CDI), so as to avoid creating 2 classes (managed bean & entity bean) and also to make use of Bean Validation so that validation can be performed on both client & server.
So should I be using a single class or not, are there any issues or should I be having my managed beans or service layer create entity beans using the data from managed beans ?
The #Named or #ManagedBean annotations are typically used to let the bean container (CDI/JSF) create an instance of a bean on demand when referenced by expression language in JSF.
For an #Entity bean, it often doesn't make that much sense to just get an arbitrary new instance. An #Entity is very strongly connected to a persistent identity. Such an entity is therefor requested from the Entity Manager and not from a bean container.
The typical pattern is to have a (slim) backing bean that's named making a call to a service (which is in turn typically #Stateless in Java EE). The service then returns entities.
In some very trivial systems people sometimes do make the service named and thus directly available to EL. However, eventually you often want to let the "backing code" generate faces messages or handle (table) selections, which are all things that should not be the concern of a pure business service.
Another common shortcut is letting the backing bean contain business code directly (e.g. the entity manager that retrieves the entities). This makes the business code hard to re-use, but if the app is trivial and there's no need for re-use you might get away with it.
But letting the entity -be- the backing bean is rare and anti to the common Java EE patterns.
Just note that the backing bean can return the entity directly, so bean-validation can still be used. There is no need whatsoever for the strange 'scatter/gather' pattern that crept up a long time ago (See the second example in this question).
E.g.
#ViewScoped
#ManagedBean
public class BackingBean {
private SomeEntity myEntity; // + getter
#EJB
private Service service;
#PostConstruct
public void init() {
myEntity = service.getSomeEntity();
}
public void save() {
service.save(myEntity);
FacesContext.getCurrentInstance().addMessage(..., ...);
}
}
Assuming SomeEntity in an #Entity annotated bean, bean validation can now be used on a Facelet like:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
>
<h:body>
<h:form>
<h:inputText value="#{backingBean.myEntity.name}" />
<h:commandButton value="Save" action="#{backingBean.save}" />
</h:form>
</h:body>
</html>
If there's a constraint on SomeEntity.name it will be validated.

JSF 2.0 pass data between beans (or pages?)

I'm working with JSF 2.0
I have a form in my admin section where I am going to select some users in a list.
The form (selectusers.xhtml) is adding these users to a list in a bean (SelectUsers.java).
After I have selected some user(s), I will pass the list of the user(s) from SelectUsers.java to another bean (AddAddressBean.java) and continue add information in another form (addadress.xhtml) which set other properties related to AddAddressBean for each user.
I do not know how to implement it. I would like that AddAddressBean.java shall be independent (so I can use it together with other beans), so I prefer that AddAddressBean.java shall not know about other beans.
Can you please help me? =)
B.R Carl
Several quick things come to mind :
Perhaps you could have a single bean only for those related pages, using #SessionScoped or the shorter CDI's #ConversationScope, or and this is the best of the three, the DeltaSpike #ViewAccessScoped
When clicking the button on page 1 where it'll take you to page 2, in the 1st bean, you can make use of Flash object to store objects you want to pass, and in the second bean's #PostConstruct method, you could get all the objects from the Flash object
If you dont mind using session scope, you can still have 2 beans, and one bean can refer to another bean using the jsf way(#ManagedProperty), or the Java EE inject way(#Inject) or the spring way if you use spring (#Autowired)
This how i implemented (used ConversationScoped as #bertie said ).
bean 1:
#Named("conversationBean1")
#ConversationScoped
public class ConversationBean1 implements Serializable {
//---start conversation----
}
bean 2:
#Named("conversationBean2")
#ConversationScoped
public class ConversationBean2 implements Serializable
{
#Inject
private ConversationBean1 conversationBean1;
}

Resources