2

I want to access values from one bean to another bean in primefaces. I defined scope @SessionScoped.

But still when accessing value in another bean, I get null.

FirstBean.java

public void setDistrict(String district) {
    System.out.println("district set District Method "+district);
    this.district = district;
}  
public String getDistrict() {
    System.out.println("district get District Method" +district);
    return district;
}

When trying to access in SecondBean.java,it is returning null.

Akshay
  • 814
  • 6
  • 19
abhishek ringsia
  • 1,970
  • 2
  • 20
  • 28
  • 2
    Are both beans JSF managed beans?? How are you trying to access the value of `FirstBean` on `SecondBean`? Please, show me some more code, so i can analyse it better. – squallsv Aug 08 '14 at 18:31
  • yes ,both are beans JSF . Accessing Something like this : firstBean.getDistrict(); (firstBean is Object of FirstBean.java) – abhishek ringsia Aug 08 '14 at 18:54
  • Ok, see my answer below, it shows you how to do it. Hope it helps! – squallsv Aug 08 '14 at 19:03

2 Answers2

4

Well, if you want to access FirstBean.java inside SecondBean.java, you can do it like this:

    ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    FirstBean firstBean = (FirstBean) elContext.getELResolver().getValue(elContext, null, "firstBean");
squallsv
  • 482
  • 2
  • 11
3

There is many ways to do that :

  • Using @ManagedProperty :

Example :

FirstBean

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "firstBean")
@SessionScoped
public class FirstBean implements Serializable {

//some Code here

SecondBean

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "secondBean")
@SessionScoped
public class FirstBean implements Serializable {

@ManagedProperty(value="#{firstBean}")
FirstBean firstBeanObject;
  • Using @Inject

Example:

FirstBean

javax.inject.Named //for bean declaration
javax.inject.Inject //for injection

@Named
@SessionScoped
public class FirstBean implements Serializable{
// your code here

SecondBean

@Named
@SessionScoped
public class SecondBean{

@Inject
FirstBean firstBean ;
//code here
  • Or get your current Object from FacesContext if using SessionScoped
Abdelghani Roussi
  • 2,707
  • 2
  • 21
  • 39