gpt4 book ai didi

java - 我可以将实体注入(inject)托管 Bean 并直接持久化吗?

转载 作者:行者123 更新时间:2023-12-01 23:36:38 25 4
gpt4 key购买 nike

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

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

}

所以这不起作用,因为 user 解析为 null。

有办法做到这一点吗?

我得到的异常(exception)是:

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

最佳答案

您需要自己创建空的用户实体。一般来说,使用 JSF 时,在 getter 中延迟创建和加载是最好的方法。只需更改 setter/getter :

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

还要记住验证。

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

关于java - 我可以将实体注入(inject)托管 Bean 并直接持久化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com