Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access property of one managed bean in another managed bean

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!

like image 907
Slay Avatar asked Sep 10 '12 17:09

Slay


People also ask

Which scope is used on managed beans which is created for every session?

Using Managed Bean Scopes. You can use annotations to define the scope in which the bean will be stored. You can specify one of the following scopes for a bean class: Application (@ApplicationScoped): Application scope persists across all users' interactions with a web application.

What is the difference between managed bean and backing bean?

1) BB: A backing bean is any bean that is referenced by a form. MB: A managed bean is a backing bean that has been registered with JSF (in faces-config. xml) and it automatically created (and optionally initialized) by JSF when it is needed.

What is the default scope of a managed bean?

Normally the default scope is the Request scope.

What is managed bean in JSF Javaserver faces?

A managed bean is created with a constructor with no arguments, a set of properties, and a set of methods that perform functions for a component. Each of the managed bean properties can be bound to one of the following: A component value. A component instance.


2 Answers

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:

  • Communication in JSF 2.0 - Injecting managed beans in each other
like image 139
BalusC Avatar answered Sep 19 '22 13:09

BalusC


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.

like image 43
Kennet Avatar answered Sep 21 '22 13:09

Kennet