在jsf页面显示bean值

Display bean value in jsf page

这是我的 LoginBean:

@ManagedBean
@ViewScoped
public class LoginBean implements Serializable {

private String email;
private String password;
private LoginBean currentUser;

CustomerService customerService = new CustomerService();

public String login() {
    currentUser = customerService.findCustomerByUserPass(email, password);

    if (getCurrentUser() != null) {
         username = customerService.getCustomerUsername(email);// i want to display this in xhtml page
        return "Home2?faces-redirect=true";
    }
    else{
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Unknown login, try again"));
        return (email = password = null);
    }
}

public boolean isLoggedIn() {
    return getCurrentUser() != null;
}
    public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

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

public LoginBean getCurrentUser() {
    return currentUser;
}

public String getUsername() {
    return username;
}

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

public LoginBean getCurrentUser() {
    return currentUser;
}
}

这是我的 jsf 页面:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
    </h:head>
    <h:body>
        <h:panelGroup rendered="#{loginBean.loggedIn}">
            <p>Welcome #{loginBean.currentUser.username} </p>
        </h:panelGroup>
    </h:body>
</html>

但结果显示为:welcome,而usernamenull

为什么?

你应该使用 sessionScoped 而不是 ViewScoped bean。

并且您的 currentUser 类型应该与您的数据库 table 类型相同,类似于 Customers,而不是 loginBean

然后您可以访问 currentUser.

的用户名值