0

这是我正在尝试做的事情:

<!DOCTYPE html>
<html
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"

        >

    <h:head>
        <title>Sign Up Page</title>
    </h:head>

    <h:body>

            <div class="well" style="margin-top: 20px">
                <h2>Please Sign Up</h2>
            </div>

            <h:form>
                <h:outputLabel for="username">User name:</h:outputLabel>
                <h:inputText id="username" value="#{signUpPage.user.username}" />
                <h:outputLabel for="password">Password:</h:outputLabel>
                <h:inputSecret id="password" value="#{signUpPage.user.password}" />
                <h:outputLabel for="passwordAgain">Password Again:</h:outputLabel>
                <h:inputSecret id="passwordAgain" value="#{signUpPage.passwordAgain}" />
                <br />
                <h:commandButton value="Submit" styleClass="btn btn-primary"
                        action="#{signUpPage.addUser}"/>
            </h:form>

    </h:body>

</html>

和托管bean:

@ManagedBean
@ViewScoped
public class SignUpPage {

    @Inject
    private User user;

    @Inject
    private UserDao userDao;

    private String passwordAgain;

    public String getPasswordAgain() {
        return passwordAgain;
    }

    public void setPasswordAgain(String passwordAgain) {
        this.passwordAgain = passwordAgain;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void addUser(){
        userDao.persistUser(this.user);
    }
}

和实体:

@Stateless
@Entity
@Table(name = "user")
public class User {

    private int id;
    private String username;
    private String password;

    @Column(name = "id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId(){
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    @Column(name = "username")
    public String getUsername(){
        return username;
    }

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

    @Column(name = "password")
    public String getPassword(){
        return password;
    }

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

}

所以这不起作用,因为用户解析为空。

有没有办法做到这一点?

我得到的例外是:

javax.servlet.ServletException: /signupPage.xhtml @34,82 value="#{signUpPage.user.username}": Target Unreachable, 'null' returned null
4

1 回答 1

3

您需要自己创建空的用户实体。通常在使用 JSF 时,在 getter 中延迟创建和加载是最好的方法。只需更改吸气剂:

public User getUser() {
    if (user == null) {
        user = new User();
    }
    return user;
}

还要记住验证。

//编辑您可能混合了注释,请阅读https://stackoverflow.com/a/12012663/221951

于 2013-09-02T18:13:56.820 回答