Injecting beans in JSF - jsf

I have a Session scoped bean
#ManagedBean(name = "ficheCultureActionController")
#SessionScoped
public class FicheCultureActionController implements Serializable {}
I want to injected in two other beans.
#ManagedBean(name = "semenceActionController")
#ViewScoped
public class SemenceActionController implements Serializable {
#ManagedProperty(value = "#{ficheCultureActionController}")
private FicheCultureActionController ficheCultureActionController;
public FicheCultureActionController getFicheCultureActionController() {
return ficheCultureActionController;
}
public void setFicheCultureActionController(FicheCultureActionController ficheCultureActionController) {
this.ficheCultureActionController = ficheCultureActionController;
}
public List<SemenceAction> getListSemenceParFicheCulture() {
if (ficheCultureActionController.getSelected() != null) {
listSemenceParFicheCulture = getFacade().getSemenceParFicheCulture();
}
return listSemenceParFicheCulture;
}
}
and
#ManagedBean(name = "engraisActionController")
#ViewScoped
public class EngraisActionController implements Serializable {
#ManagedProperty(value = "#{ficheCultureActionController}")
private FicheCultureActionController ficheCultureActionController;
public FicheCultureActionController getFicheCultureActionController() {
return ficheCultureActionController;
}
public void setFicheCultureActionController(FicheCultureActionController ficheCultureActionController) {
this.ficheCultureActionController = ficheCultureActionController;
}
}
but the property returns null in the method getListSemenceParFicheCulture().

Related

How to access a Managed Bean from WebSocket class

I want to access an #SessionScoped managed bean from WebSocket Endpoint class.
I tried
#ManagedProperty(value = "#{bean}")
private Bean bean;
in WebSocket class, but it throws:
org.apache.tomcat.websocket.pojo.PojoEndpointBase onError
SEVERE: No error handling configured for [WebSocket] and the following error occurred
java.lang.NullPointerException
#ServerEndpoint("/ws")
public class WebSocket
private Session session;
#ManagedProperty(value = "#{bean}")
private Bean bean;
#OnOpen
public void connect(Session session) {
System.out.println("BAGLANTÄ° KURULDU");
this.session = session;
}
#OnClose
public void close() {
System.out.println("BAGLANTÄ° KAPANDI");
this.session = null;
}
#OnMessage
public void message(String message) {
System.out.println("Client'ten Gelen Mesaj= " + message);
//this.session.getAsyncRemote().sendText(message + bean.getTc());
System.out.println(bean.getTc());
}
#ManagedBean(name = "bean", eager = true)
#SessionScoped
public class Bean
private String tc,sifre,name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTc() {
return tc;
}
public void setTc(String tc) {
this.tc = tc;
}
public String getSifre() {
return sifre;
}
public void setSifre(String sifre) {
this.sifre = sifre;
}

Set value to ManagedProperty

I'm trying to set a value to my ManagedProperty but I'm getting the null result when I try to print this.
I'd like to set the Bean Class to use it in my query.
I've been tryin' set String, Class, but all the times it returned a null value.
Can anyone help me?
#ManagedBean
public class FilialBean extends BaseBean implements Serializable{
private Filial filial;
private List<Filial> filiais;
#ManagedProperty("#{entidadeService}")
private EntidadeService service;
#PostConstruct
public void init(){
service.setFaces(Filial.class);
filial = new Filial();
filiais = (List<Filial>) (List) service.getbasesEntidades();
}
//GETTERS AND SETTERS
}
#ManagedBean(name="entidadeService", eager=true)
#ApplicationScoped
public class EntidadeService implements Serializable{
private List<EntidadeBase> basesEntidades;
private Class faces;
#PostConstruct
public void init(){
System.out.println(faces.getSimpleName());
try{
EntityManager manager = JPAUtil.getEntityManager();
Query query = manager.createQuery("SELECT e FROM Filial e WHERE e.ativo = :ativo");
query.setParameter("ativo", true);
this.basesEntidades = query.getResultList();
}
catch(Exception e){
e.printStackTrace();
}
}
public List<EntidadeBase> getbasesEntidades() {
return basesEntidades;
}
public Class getFaces() {
return faces;
}
public void setFaces(Class faces) {
this.faces = faces;
}
}
Have you check that #ManagedBean has same package in both classes?
I ran into same problem, a property with null value executing Post Construct method and this is the problem, one class had javax.annotation.ManagedBean (CDI) annotation and the other had javax.faces.bean.ManagedBean (JSF) annotation.
In my case I needed both classes with JSF annotations...

Passing instance variable between managed beans

I am trying to get the UserBeans instance variables from LoginBean class. I want to use instance variable of Userbean into LoginBean class. Someone helps me.
Here, UserBean.java class :
#ManagedBean
#SessionScoped
public class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And, Here's LoginBean.java class :
public class LoginBean {
public String login_check() {
if(name.equals("mahbub")){
return "success";
}else
return "fail";
}
Inject your UserBean class into LoginBean class and generate its getter and setter. So, your code should look like this.
public class LoginBean {
#ManagedProperty(value = "#{userBean}")
private UserBean userBean;
public String login_check() {
if(name.equals("mahbub")) {
return "success";
} else {
return "fail";
}
}
// userBean getter and setter here
}
Hope this would work for you. Cheers!
Use something like this
public class LoginBean {
#ManagedProperty(value = "#{userBean}")
private UserBean userBean;
public String login_check() {
if(userBean.getName().equals("mahbub")){
return "success";
}else
return "fail";
}
}
But you should rethink your design pattern

How to use CDI and Dependency Injection

I want to use the same object "User" within the Farma and the Pata objects. The object user is first initialized inside the Farma object. I tried to annotated with #inject, but the object user inside Pata, has the name with null value. Please, can anyone help me understand what I am doing wrong? Thank!
#Named
#SessionScoped
public class Farma implements Serializable {
#Inject private User user;
#PostConstruct
public void initialize(){
user.setName("MyName");
}
// Getters and Setters
}
#Named
#SessionScoped
public class Pata implements Serializable {
#Inject private User user;
public String getFuzzyName() {
// Here I want to use the object "user" with the name "MyName" to do some logic
}
// Getters and Setters
}
public class User implements Serializable {
private String name;
// Getters and Setters
Just scoping a User object won't allow you to initialize it.
Use "producer method" to control bean's creation.
Try this:
#SessionScoped
public class Pata implements Serializable {
#Inject
#SessionUser // inject here using the producer method
private User user;
public String getFuzzyName() {
return user.getName();
}
}
#SessionScoped
public class Farma implements Serializable {
#Produces
#SessionUser // qualifier to tie injection points to this method
#SessionScoped // to ensure it will be called once per session for any number of injection points
public User produceUser() {
System.out.println("Creating user");
User u = new User();
u.setName("User");
return u;
}
}
////// that's your custom qualifier, it's in a separate file
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({METHOD, FIELD, PARAMETER, TYPE})
public #interface SessionUser {}
// no scopes here, it is defined by the producer method
public class User implements Serializable {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
You need to understand scoping of CDI beans. The default scope, if none is specified, is the #Dependent scope, which means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean).
In this case it means that the user in Farma only exists for the Farma class and lives for the life of the Farma class.
The user in Pata is a different instance, and its lifecycle matches that of Pata.
You need to properly scope the User object.
As axiopisty said, adding #Named #SessionScoped is the correct way.
I tried and it works great.
#Named
#SessionScoped
public class Pata implements Serializable {
#Inject
private User user;
public String getFuzzyName() {
System.out.println(user.getName());
return user.getName();
}
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
}
#Named
#SessionScoped
public class Farma implements Serializable {
#Inject
private User user;
#PostConstruct
public void initialize() {
user.setName("MyName");
}
// Getters and Setters
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
}
#Named
#SessionScoped
public class User implements Serializable {
private String name = "Default";
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
<h:outputText value="#{farma}"></h:outputText><br />
<h:outputText value="#{pata}"></h:outputText><br />
<h:outputText value="#{pata.fuzzyName}"></h:outputText>

Why is an exception thrown when an #ManagedProperty is referenced?

I have a JSF web application with a view-scoped bean and a session-scoped bean. I'd like to modify the session bean's members from the view bean, and I followed this guide from a certain well-known JSF guy, but I can't seem to get it to work without a runtime exception. The reference to the managed session bean, "home" is null when referenced, similar to this question except I've already followed the advice of the accepted answer.
package brian.canadaShipping;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
#ManagedBean(name= "requestBean")
#ViewScoped
public class CpstcRequestBean implements Serializable {
#ManagedProperty(value="#{home}")
private CpstcHomeBean homeBean;
public CpstcHomeBean getHomeBean() {
return homeBean;
}
public void setHomeBean(CpstcHomeBean homeBean) {
this.homeBean = homeBean;
}
private static final long serialVersionUID = -5066913533772933899L;
public String testVar = "hello world";
private boolean displayOutput = false;
public boolean isDisplayOutput() {
return displayOutput;
}
public void setDisplayOutput(boolean displayOutput) {
this.displayOutput = displayOutput;
}
public String getTestVar() {
return testVar;
}
public void setTestVar(String testVar) {
this.testVar = testVar;
}
public CpstcRequestBean()
{
System.out.println("TEST: " + homeBean.toString());
System.out.println("Hello, ResuestBean!");
}
}
The first bit of my "home" bean is as follows:
#ManagedBean(name= "home")
#SessionScoped
public class CpstcHomeBean implements Serializable {
...
UPDATE: I've followed Jordan's suggestions and I have the following in my view-scoped bean:
#ManagedBean(name= "requestBean")
#ViewScoped
public class CpstcRequestBean implements Serializable {
#Inject #Named("home") CpstcHomeBean homeBean;
public CpstcHomeBean getHomeBean() {
return homeBean;
}
public void setHomeBean(CpstcHomeBean homeBean) {
this.homeBean = homeBean;
}
public CpstcRequestBean()
{
System.out.println("TEST: " + homeBean.toString());
System.out.println("Hello, ResuestBean!");
}
...
as well as this in my session-scoped bean:
#Named("home")
#SessionScoped
public class CpstcHomeBean implements Serializable {
...
yet my "home" bean reference is still null. Any ideas?
UPDATE 2: It turns out that you must use #Named in both classes, not just the injected class. My web app now loads but some elements are blank. In my console log, I see, "Target Unreachable, identifier 'home' resolved to null." I'm running on Tomcat 7, if that affects things. Any ideas?
You can either change your session bean's #ManagedBean to #Named and then just inject it into your view scoped bean OR you can reference the session bean as is like this:
FacesContext fc = FacesContext.getCurrentInstance()
private CpstcHomeBean homeBean = (CpstcHomeBean) fc.getApplication().evaluateExpressionGet(fc, "#{home}", CpstcHomeBean.class);

Resources