![](/img/trans.png)
[英]How to add the ID of an object to a hidden input of a form with Thymeleaf
[英]Passing thymeleaf information to a hidden form
我正在嘗試從百里香列表中傳遞信息,並嘗試將其添加到數據庫中。 我正在從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";
}
}
提前Thx
首先,讓我們更改表格。 您不需要向其添加新對象,因為您已經在其中遍歷了它們。 這樣,您還可以避免必須使用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";
}
這些更改應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.