How to have one instance of Backing Bean per Browser tab? - jsf

My environment: Java 7/JSF 2.1/PrimeFaces 6.1.
My goal: to have a certain page of my application instantiated many times, one for each browser tab, each one with a different context.
My problem: everytime I open a second browser tab requesting from the same url, but with different object id, the previous one is destroyed, so only one backing bean instance is kept alive.
How do I know that: In my backing bean I have one method annotated with #PosConstruct and other with #PreDestroy, so I can track the life cicle of the instances.
My backing bean is annotated as follows:
#ViewController
public class MyBackingBeanMB extends AbstractBackingBeanMB {
private static final long serialVersionUID = 1L;
// many fields and methods
}
The #ViewController annotation is provided by the application framework I have to use. Such an annotation is declared as:
#Named
#Controller
#Stereotype
#ViewScoped // For me, this should do the trick, but...
#Target(value={TYPE})
#Retention(value=RUNTIME)
#Inherited
public #interface ViewController {
}
Update 1:
The #Controller annotation is also provided by the framework I use and is declared as:
#InterceptorBinding
#Inherited
#Target({ TYPE, METHOD })
#Retention(RUNTIME)
public #interface Controller {
}
Any ideas of what could be wrong?
TIA.

After some digging in the Internet I found Apache DeltaSpike, which provider a new kind of managed bean scope, WindowScoped.
Managed beans annotated with #WindowScoped` operate just like I wanted, providing me with the exact behaviour I needed and it is absolutely compatible with the framework I have to use.

Related

need clarification on JSF and managed beans

i have some behavior im unable to understand,
so i started to recently learn JSF, im using TOMCAT 6, now i created JSF file , and i created two Managed Beans under different packages, but each bean have the same name.
1. First bean is com.app.TestBean.
2. Second bean is jsftest.TestBean.
now when i call my JSF page, i get to invoke the first bean, if i restart the TOMCAT , i get the result of the second bean, can any body explain what im doing wrong here ?
Unless you specified their name explicitely, the beans have their name/id assigned based on they class name.
So TestBean would be: testBean
So if you have conflicting class names, you need to explicitely specify their (different) name.
For example if you are using the annotation (which i suspect is the case), you need to do
package com.app;
#ManagedBean("testBean1")
public class TestBean {
...
}
and the other bean
package jsftest;
#ManagedBean("testBean2")
public class TestBean {
...
}
And then use either #{testBean1} or #{testBean2}

CDI Bean Scoping during Injection is not working

I want to give on-the-go scope to a pojo bean in CDI during injection.
I created a plain bean and injected the same as #javax.enterprise.context.ApplicationScoped in a #javax.faces.bean.ViewScoped Managed Bean like this:
#Inject
#ApplicationScoped
Pojo pojo;
// POJO Class
Class Pojo {
private String var;
public Pojo() {
}
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
}
The Pojo bean's populated values could not be restored in a new view bean when I inject using the same syntax.
But it works when I use #ApplicationScoped in the class declaration instead, followed by non-scoped injection, like this:
#ApplicationScoped
Class Pojo {
private String var;
Injection:
#Inject
Pojo pojo;
The former case gets resolved when I make a producer and qualifier but I feel this would be an overhead I should do without. Being new to CDI, I want to ask what I am really missing here.
Scope and Context management are a very powerful feature in CDI. It is also part of the business logic of the components (an #ApplicationScoped bean won't be developed the same way than a #RequestScoped), that's why the scope is link to bean definition.
An injection point is only a place where you consume a bean and not a place where you define it, so there is no way to define the scope of a bean at the injection point at spec level.
Now if you really want to use this feature you could develop a portable extension to add this possibility. But you'll probably have to work on a qualifier system as well since scope is not used in bean resolving process (i.e. 2 beans with the same type in different scope will be in conflict for a given injection point if they don't have specific qualifier).

Netbeans warning: no enabled eligible for injection beans are found

I have two beans. First bean languageOfSystem:
#Named(value = "languageOfSystem")
#SessionScoped
public class LanguageOfSystem implements Serializable {
#Inject private JsfUtils eeJsfUtils;
and the second bean, userBb:
#Named(value = "userBb")
#SessionScoped
public class UserBb implements Serializable, LangUpdInterface {
#EJB
private EjbUtils ejbUtils;
#EJB
private PuserFacade puserFacade;
#Inject
private Direction direction;
#Inject
private PortfelDao portfelDao;
#Inject
private LanguageOfSystem languageOfSystem;
I inject languageOfSystem into userBb, and NetBeans IDE gives me warning in line with that injection:
no enabled eligible for injection beans are found
But I'm able to call methods from languageOfSystem in userBb and it works fine. So is this warning important and should I change smth?
And the second question. I use in this case observer design pattern, where userBb is dependent and languageOfSystem is the subject which has a list of dependents. I register userBb in subject list by calling appropriate method from languageOfSystem. Is it right when it comes to the two session beans?
But I'm able to call methods from languageOfSystem in userBb and it
works fine.
Your code does not look wrong - and it works. So this seems to be a Netbeans issues.
And the second question. I use in this case observer design pattern,
where userBb is dependent and languageOfSystem is the subject which
has a list of dependents. I register userBb in subject list by calling
appropriate method from languageOfSystem. Is it right when it comes to
the two session beans?
Are you aware that the CDI spec includes a powerful and typesafe implementation of the observer pattern? You definitely should check this out.
And two more things to mention here:
#Named(value = "languageOfSystem")
#Named(value = "userBb")
The value you are providing is already default. So you can leave it
out and simply write #Named instead.
Regarding the code you are posting: #Named is not required at all -
all it does is providing an EL name for use in JSF. Your code will
work just as good if you skip #Named altogether...
As to your first question:
This is a known netbeans bug (see here and here). However, the discussion in the first link indicates that it is rather an issue of the weld implementation and Netbeans' warning is according to the specification.
Nevertheless the bugzilla file says it will be fixed in Netbeans v7.2.
Until then you can still disable the warning (Tools --> Options --> Editor --> Hints)

Bean annotations like #ManagedProperty and #PostConstruct doesn't work when manually instantiating the bean from another bean

I instantiated a request bean from another request bean,
new LoginManager();
But the property which is annotated with #ManagedProperty doesn't get the value from the asked reference, only in case of instantiation through the above way. It just contains null, causing NPE later in code. Also #PostConstruct won't be invoked. Why is it so & how should I deal with this?
#ManagedBean(name = "loginManager")
#RequestScoped
public class LoginManager {
private String userid;
private String password;
#ManagedProperty(value="#{currentSession}")
private UserSessionManager userSession;
}
But userSession can't read from the session scoped bean when this bean was instantiated using: new LoginManager();
However I can read the value using FacesContext!
You should not manually instantiate (manage) beans using new operator. You should let JSF do the job of managing the beans and instead grab the JSF-managed (JSF-instantiated) instance.
Either by #ManagedProperty in the bean where you need it:
#ManagedProperty("#{loginManager}")
private LoginManager loginManager;
Or by invoking EL programmatically (which is pretty borderline in your particular case):
LoginManager loginManager = context.getApplication().evaluateExpressionGet(context, "#{loginManager}", LoginManager.class);
// ...
If you insist in instantiating and managing the bean yourself, you should do all dependency injections yourself, also invoking the #PostConstruct yourself, if any, and finally also putting the bean in the desired scope yourself. E.g.
LoginManager loginManager = new LoginManager();
loginManager.setUserSession(userSession);
// Now use reflection to find and invoke #PostConstruct method.
// Finally store in the map which conforms the bean's scope.
externalContext.getRequestMap().put("loginManager", loginManager);
This boilerplate is exactly what JSF is supposed to take away from your hands. Make use of it.

Refresh managed session bean in JSF 2.0

After I commit some data into the database I want my session beans to automatically refresh themselves to reflect the recently committed data. How do I achieve this when using managed session beans in JSF 2.0?
Currently I have to restart the web server in order for the sessions to clear and load anew again.
2 ways:
Put them in the view scope instead. Storing view-specific data sessionwide is a waste. If you have a performance concern, you should concentrate on implementing connection pooling, DB-level pagination and/or caching in the persistence layer (JPA2 for example supports second level caching).
#ManagedBean
#ViewScoped
public class FooBean {
// ...
}
Add a public load() method so that it can be invoked from the action method (if necessary, from another bean).
#ManagedBean
#SessionScoped
public class FooBean {
private List<Foo> foos;
#EJB
private FooService fooService;
#PostConstruct
public void load() {
foos = fooService.list();
}
// ...
}
which can be invoked in action method inside the same bean (if you submit the form to the very same managed bean of course):
public void submit() {
fooService.save(foos);
load();
}
or from an action method in another bean (for the case that your managed bean design is a bit off from usual):
#ManagedProperty("#{fooBean}")
private FooBean fooBean;
public void submit() {
fooService.save(foos);
fooBean.load();
}
This of course only affects the current session. If you'd like to affect other sessions as well, you should really consider putting them in the view scope instead, as suggested in the 1st way.
See also:
How to choose the right bean scope?

Resources