gpt4 book ai didi

java - 为什么我的表单没有在 spring boot 中传递信息

转载 作者:行者123 更新时间:2023-11-30 06:41:56 24 4
gpt4 key购买 nike

您好,我正在以表格形式传递信息,一切运行正常,但是当我填写表格时,它没有传递信息,我收到了这个错误。

出现意外错误(类型=内部服务器错误,状态=500)。原因:org.hibernate.exception.ConstraintViolationException:无法执行语句Caused by: java.sql.SQLIntegrityConstraintViolationException: 列 'movie_id' 不能为空

我使用的代码如下:

@PostMapping("/save")
public String save(Movie movie) {
savedMovie.save(movie);
return "redirect:/LatestMovies";
}

 <form th:action="@{/save}" method="post" >
<p><input type="text" id="movie_id" name="movie_id" value="" /></p>
<p><input type="text" id="movie_name" name="movie_name" value="" /></p>
<p><input type="submit" value="save" /></p>
</form>

我相信所有其他代码都是正确的,因为如果我尝试呈现数据库信息,我没有问题。

更新

这是完整的html代码。

<div class="container">   
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="LatestMovies : ${latestMovies}">
<td th:text="${LatestMovies.id}"></td>
<td th:text="${LatestMovies.movieName}"></td>
<td>
<form th:action="@{/save}" method="post" th:object="${newMovie}">
<p><input type="text" id="movie_id" th:field="*{movie_Id}"/></p>
<p><input type="text" id="movie_name" th:field="*{movie_Name}"/></p>
<p><input type="submit" value="save" /></p>
</form>
</td>

</tr>
</table>

最佳答案

您的 Controller 需要一个 Movie 对象,但它正在接收其他内容,然后生成一个空 Movie 对象。您需要在表单中使用 th:object 才能正确发送相应的类。首先,让我们向您的 Controller 添加一个新的 @ModelAttribute,以便您的表单可以自动将您的 Movie 对象映射到您的表单中。

Controller

// In order to use th:object in a form, we must be able to map a new entity to that form.
// In this case we return a Movie entity.
@ModelAttribute(value = "newMovie")
public Movie newMovie() {return new Movie();}

现在,让我们更改您的表单,以便它实际发送 Movie 对象。

<form th:action="@{/save}" method="post" th:object="${newMovie}">
<p><input type="text" id="movie_id" th:field="*{movie_id}"/></p>
<p><input type="text" id="movie_name" th:field="*{movie_name}"/></p>
<p><input type="submit" value="save" /></p>
</form>

请注意,我还更改了您输入中的 name 属性,用于 th:field。请记住,为了使其工作,每个字段的名称必须与您的对象中的名称完全匹配。

更新

如果你想为你的表单设置默认值,而不使用 js 并且因为你不能将 th:fieldth:value 组合,您可以在 Controller 中设置对象的属性。

@ModelAttribute(value = "newMovie")
public Movie newMovie() {
Movie movie = new Movie();
movie.setName("Test");
return movie;
}

更新 2

如果您想要将 Thymeleaf 列表的当前迭代放入您的表单中,您可以执行以下操作。

<div class="container">   
<table class="table table-hover">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="LatestMovies : ${latestMovies}">
<td th:text="${LatestMovies.id}"></td>
<td th:text="${LatestMovies.movieName}"></td>
<td>
<form th:action="@{/save}" th:object="${LatestMovies}" method="post">
<p><input type="hidden" th:value="*{id}"/></p>
<p><input type="hidden" th:value="*{movieName}"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</td>
</tr>
</table>

关于java - 为什么我的表单没有在 spring boot 中传递信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54278668/

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