Question

I have problem with JSF 2 property binding and honestly I hit a wall here..

What I want to accomplish is this: a request-scoped bean (loginBean) process login action and stores username in the session-scoped bean (userBean). I want to inject userBean into loginBean via @ManagedProperty, but when loginBean.doLoginAction is called, userBean is set to null.

Here is the code:

UserBean class

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

@ManagedBean
@SessionScoped
public class UserBean {

private String username;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public boolean isLogged() {
    if (username != null)
        return true;
    return false;
}
}

loginBean class:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class LoginBean {

@ManagedProperty(value = "userBean")
private UserBean userBean;

private String name;
private String password;    

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public UserBean getUserBean() {
    return userBean;
}

public void setUserBean(UserBean userBean) {
    this.userBean = userBean;
}

public String doLoginAction() {
    if (name.equals("kamil") && password.equals("kamil")) {
        userBean.setUsername(name);
    }
    return null;
}

public String doLogoutAction() {
    return null;
}
}           

Any ideas what I'm doing wrong here?

Was it helpful?

Solution

You need to specify an EL expression #{}, not a plain string:

@ManagedProperty(value = "#{userBean}")
private UserBean userBean;

or, shorter, since the value attirbute is the default already:

@ManagedProperty("#{userBean}")
private UserBean userBean;

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top