ManagedProperty无法正常工作

时间:2012-01-27 16:01:03

标签: jsf-2 managed-bean

我有JSF 2属性绑定的问题,说实话,我在这里碰壁了..

我想要完成的是:请求范围的bean(loginBean)进程登录操作并将用户名存储在会话范围的bean(userBean)中。我想通过@ManagedProperty将userBean注入loginBean,但是当调用loginBean.doLoginAction时,userBean被设置为null。

以下是代码:

UserBean类

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类:

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;
}
}           

我在这里做错了什么想法?

1 个答案:

答案 0 :(得分:6)

您需要指定EL表达式#{},而不是普通字符串:

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

或更短,因为value attirbute已经是默认值:

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

另见: