8

I have a managed bean (SessionScope as follow)

@ManagedBean(name="login")
@SessionScoped
public class Login implements Serializable {

   private String userSession;
   public Login(){
   }
}

In this managedbean, somewhere in the login function, i store the email as a session.

I have another managed bean called ChangePassword (ViewScoped). I need to access the value of the email which is stored in the userSession.

The reason of doing so is that i need to find out the current userSession(email) before i can complete the change password function. (Need change password for that specific email)

How do i do so? New to JSF, appreciate any help!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Slay
  • 1,285
  • 4
  • 20
  • 44

4 Answers4

17

Just inject the one bean as a managed property of the other bean.

@ManagedBean
@ViewScoped
public class ChangePassword {

    @ManagedProperty("#{login}")
    private Login login; // +setter (no getter!)

    public void submit() {
        // ... (the login bean is available here)
    }

    // ...
}

See also:

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

In JSF2, I usually use a method like this:

public static Object getSessionObject(String objName) {
    FacesContext ctx = FacesContext.getCurrentInstance();
    ExternalContext extCtx = ctx.getExternalContext();
    Map<String, Object> sessionMap = extCtx.getSessionMap();
    return sessionMap.get(objName);
}

The input parameter is the name of your bean.

Kennet
  • 5,736
  • 2
  • 25
  • 24
  • 1
    While this works, this is a rather clumsy approach to get a session scoped managed bean in a managed bean. – BalusC Sep 10 '12 at 18:24
  • 1
    Still learning... and you, @BalusC, usually solve my problems. (In most cases others have already asked what I want to ask about, and you answered.) – Kennet Sep 11 '12 at 07:04
0

if your session scoped bean is like this :

@ManagedBean(name="login")
@SessionScoped
public class Login implements Serializable {

   private String userSession;
   public Login(){
   }
}

you can access the values of this bean like :

@ManagedBean(name="changePassword")
@ViewScoped
public class ChangePassword implements Serializable {

   @ManagedProperty(value="#{login.userSession}")
   private String userSession;
   public ChangePassword (){
   }
}
erencan
  • 3,725
  • 5
  • 32
  • 50
0
public static Object getSessionObj(String id) {
   return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(id);
}

public static void setSessionObj(String id,Object obj){
   FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(id, obj);
}

Add them in your managed bean :

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254