Thymeleaf 注册页面 - 执行处理器“org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor”期间出错

2023-12-29

我正在为一个网站制作一个注册页面。我知道为了创建新用户,需要一个 id,所以我们有这个字段:

<input type="hidden" th:field="{*id} />

但是,当我转到该页面时,我收到了本文标题中提到的错误。

这是有问题的表格:

<form th:action="@{/users/register}" th:object="${user}" class="form-signin" method="POST">
    <h2 class="form-signin-heading">Register</h2>
    <input type="hidden" th:field="*{id}" />
    <label for="inputUsername" class="sr-only">Username*</label>
    <input type="text" th:field="*{username}" name="username" id="inputUsername" class="form-control" placeholder="Username" required="required" autofocus="autofocus" />
    <label for="inputEmail" class="sr-only">Email Address*</label>
    <input type="text" th:field="*{email}" name="email" id="inputEmail" class="form-control" placeholder="Email address" required="required" autofocus="autofocus" />
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" th:field="*{password}" name="password" id="inputPassword" class="form-control" placeholder="Password" required="required" />
    <label for="inputConfirmPassword" class="sr-only">Confirm Password</label>
    <input type="password" th:field="${confirmPassword}" name="confirmPassword" id="inputConfirmPassword" class="form-control" placeholder="Confirm password" required="required" />
    <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>

这是我的用户控制器:

@RequestMapping("/register")
public String registerAction(Model model) {
    model.addAttribute("user", new User());
    model.addAttribute("confirmPassword", "");
    return "views/users/register";
}

@RequestMapping(value="/register", method = RequestMethod.POST)
public String doRegister(User user) {
    User savedUser = userService.save(user);
    return "redirect:/"; //redirect to homepage
}

用户实体的第一部分:

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

// Default constructor require by JPA
public User() {}

@Column(name = "id")
@Id @GeneratedValue
private Long id;

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

public long getId() {
    return id;
}

据我所知,这里没有任何问题,所以我被困住了。

我正在遵循这个例子:https://github.com/cfaddict/spring-boot-intro https://github.com/cfaddict/spring-boot-intro

有任何想法吗?


问题在于您声明 id 属性的方式。该字段使用引用类型 Long,该类型为 null。 getter 使用原始 long。当 Spring 访问 id 字段时,它会尝试取消装箱空值,从而导致错误。将您的域类更改为

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

    // Default constructor required by JPA
    public User() {}

    @Id
    @Column(name = "id")
    @GeneratedValue
    private Long id;

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

    public Long getId() {
        return id;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Thymeleaf 注册页面 - 执行处理器“org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor”期间出错 的相关文章

随机推荐