我正在尝试从百里香列表中传递信息,并将其添加到数据库中。 我正在从tmdb获取数据,并且它将不断变化,因此我将获取的信息显示到端点“ / LatestMovies”,该信息未保存在db中,应该保存在以太中。所以我想为custumer添加一个保存按钮以添加列出的电影。(它很简单,它只有movieid和moviename) 显示列出的电影我没有问题,并且工作正常,但是当我添加隐藏表单时出现错误。我当前的代码是这样的:
<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 action="#" th:action="@{/LatestMovies}" th:object="${addMovies}" method="post">
<p><input type="hidden" th:field="*{id}" th:attr="value = ${LatestMovies.id}" /></p>
<p><input type="hidden" th:field="*{movieName}" th:attr="value = ${LatestMovies.movieName}" /></p>
<p><input type="submit" value="Submit" /></p>
</form>
</td>
</tr>
</table>
@Controller
public class LatestMoviesController {
@Autowired
private LatestMoviesDao listOfMovies;
@Autowired
private savedMoviesDao movieRepo;
@GetMapping("/LatestMovies")
public String prueba(Model model) {
TmdbMovies movies = new TmdbApi("22914f477aaa3e7f86c6f5434df8d1eb").getMovies();
ResultsPage<MovieDb> movie = movies.getPopularMovies("en", 1);
for(int i=0; i <= 19; i++){
int movieId = movie.getResults().get(i).getId();
String movieName = movie.getResults().get(i).toString();
listOfMovies.save(new LatestMovies(movieId, movieName));
}
model.addAttribute("latestMovies", listOfMovies.findAll());
return "index";
}
@PostMapping("/LatestMovies")
public String save(@ModelAttribute("addMovies") Model model, SavedMovies addMovies) {
movieRepo.save(addMovies);
return "index";
}
}
提前谢谢
答案 0 :(得分:0)
首先,让我们更改表格。您不需要向其添加新对象,因为您已经在其中遍历了它们。这样,您还可以避免必须使用th:attr
手动为每个字段添加值。我们要做的是分别发送所需的参数,然后用它们构建我们的电影对象。
<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="@{/LatestMovies}" method="post">
<p><input type="hidden" th:value="${LatestMovies.id}" name="id"/></p>
<p><input type="hidden" th:value="${LatestMovies.movieName}" name="name"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</td>
</tr>
</table>
</div>
现在,在您的控制器上进行以下修改。
@PostMapping("/LatestMovies")
public String save(@RequestParam("id") Integer id, @RequesParam("name") String name) {
SavedMovies movie = new SavedMovies();
movie.setId(id);
movie.setName(name);
movieRepo.save(movie);
return "index";
}
这些更改应该可以解决问题。