【发布时间】:2020-04-12 09:41:28
【问题描述】:
我的问题很奇怪。我有一个小表单,它有两个下拉菜单来选择项目并创建一个包含这两个的新项目。下面是对象最基本的值:
public class Rental {
private Integer id;
private Movie movie;
private Client client;
}
问题如下。我的 HTML 文件有这种形式:
<h1>Add New Rental</h1>
<form action="#" th:action="@{/rentals/add}" th:object="${rental}" method="post" >
<div class="form-group col-md-8">
<label for="client" class="col-form-label">Client</label>
<select class="form-control" th:field="*{client}" id="client">
<option disabled selected="selected" value="0">Select Client</option>
<option th:each="clnt : ${listClients}" th:value="${clnt}" th:text="${clnt.name + ' ' + clnt.lastname}"></option>
</select>
</div>
<div class="form-group col-md-8">
<label for="movie" class="col-form-label">Movie</label>
<select class="form-control" th:field="*{movie}" id="movie">
<option disabled selected="selected" value="0">Select Movie</option>
<option th:each="mov : ${listMovies}" th:value="${mov}" th:text="${mov.title}"></option>
</select>
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-primary" value=" Submit ">
</div>
</form>
而处理这个页面的控制器如下:
@RequestMapping(path = "/rentals", method = RequestMethod.GET)
public String listRentals(Model model) {
model.addAttribute("rental", new Rental());
model.addAttribute("listRentals", this.MCRService.getRentals());
model.addAttribute("listClients", this.MCRService.getClients());
model.addAttribute("listMovies", this.MCRService.getMovies());
return "rentals";
}
@RequestMapping(value = "/rentals/add", method = RequestMethod.POST)
public String addRental(@ModelAttribute("rentals") Rental rent) {
Client client = this.MCRService.getClient(rent.getClient().getId());
Movie movie = this.MCRService.getMovie(rent.getMovie().getId());
if (((client.getRentalCollection().size() + 1) * 10) <= client.getBalance()) {
client.addMovie(movie);
this.MCRService.updateClient(client);
this.MCRService.updateMovie(movie);
}
return "redirect:/rentals";
}
但是当我运行它时,同时选择一个客户端和一个电影,然后我按下提交,控制台抛出一个NullPointerException,结果客户端和电影都是null,这很奇怪,因为我'在选择中使用整个对象。我在这里做错了什么? th:value 和 th:field 有什么问题吗?还是我的代码有缺陷?任何帮助表示赞赏!
【问题讨论】:
标签: spring-boot spring-data-jpa thymeleaf