【发布时间】:2017-10-22 13:45:27
【问题描述】:
我有传递对象列表的表单和相应的控制器。之后,此列表将作为属性重定向到另一个方法并显示在网站中。之后,我想通过 carSearchResult.html 文件中的表单将此列表中的对象传递给控制器。我试图像这里描述的那样做Spring and Thymeleaf: Sending an object to a controller from a th:each table,但它不能正常工作。它正在向控制器发送一个对象,但字段属性和模型设置为空白(但它们不为空)。
搜索汽车表格
<form action="#" th:action="@{/user/searchCar}" method="post">
<input type="radio" name="type" value="hatch" /> Hatchback <br/>
<input type="radio" name="type" value="sedan" /> Sedan <br/>
<input type="radio" name="type" value="combi" /> Kombi <br/>
<input type="radio" name="type" value="sport" /> Sport <br/>
<input type="radio" name="type" value="cabrio" /> Cabrio <br/>
<input type="text" name="dailyPrice" placeholder="Price" /> <br/>
<input type="date" name="dateOfRent" placeholder="Date of rent" /> <br/>
<input type="date" name="dateOfReturn" placeholder="Date of return" /> <br/>
<input type="submit" value="Show" />
</form>
searchCar post请求的控制器方法
@PostMapping("/user/searchCar")
public String searchCar(Model model, @RequestParam String type, @RequestParam double dailyPrice,
@RequestParam Date dateOfRent, @RequestParam Date dateOfReturn, RedirectAttributes redirectAttr) {
List<Car> allCarsList = carDao.getAllCars(type, dailyPrice, dateOfRent, dateOfReturn);
redirectAttr.addFlashAttribute("carList", allCarsList);
return "redirect:/user/carSearchResults";
}
列表重定向的方法
@GetMapping("/user/carSearchResults")
public String showCarSearchResults(Model model) {
model.addAttribute("car", new Car());
return "user/carSearchResults";
}
显示列表的表单
<div th:each="car: ${carList}">
<h3 th:text="${car.producer}"></h3>
<h3 th:text="${car.model}"></h3>
<form action="#" th:action="@{/user/showCarDetails}" method="post" th:object="${car}">
<input type="hidden" th:field="*{producer}" /> <br/>
<input type="hidden" th:field="*{model}" /> <br/>
<input type="submit" value="Show" />
</form>
</div>
我想从 th:each 循环向其发送对象的方法
@PostMapping("/user/showCarDetails")
public String showCarDetails(@ModelAttribute Car car) {
System.out.println(car);
return "user/showCarDetails";
}
在控制台中打印有关汽车的信息后,我收到下面的对象。看起来它已通过但参数为空格。谁能帮我?非常感谢。
Car [id=null, producer=, model=, seatsNumber=null, type=null, registrationNumber=null, dailyPrice=null, description=null]
编辑
我已更改表格。带有 th:attr 和 th:value 的选项有效,但我真的不明白为什么 th:field 不起作用以及它们之间的区别是什么。据我了解,th:value 是 th:field 的某种旧版本?
<div th:each="car: ${carList}" th:object="${car}">
<h3 th:text="*{producer}"></h3>
<h3 th:text="*{model}"></h3>
<form action="#" th:action="@{/user/showCarDetails}" method="post">
<input type="hidden" th:value="*{producer}" name="producer" /> <br/> <!-- It works -->
<input type="hidden" th:attr="value=*{producer}" name="producer" /> <br/> <!-- It works -->
<input type="hidden" th:field="*{producer}" /> <!-- It does not work -->
<input type="submit" value="Pokaż" />
</form>
</div>
【问题讨论】:
-
您不会将对象从 thymeleaf 传递给控制器。仅从控制器到百里香叶。您通过 POST 调用从 HTML 表单向控制器发送一些内容。你能澄清你的问题吗?
-
但是通过 @ModelAttribute 注释我从通过 POST 调用发送的参数接收对象?