![](/img/trans.png)
[英]Spring Boot & Thymeleaf,passing variables to the controller
[英]Spring Controller + Thymeleaf form generated by foreach (cannot get access to variables)
在 thymeleaf 中,我生成带有报价的“订单簿”。 它是用另一个 controller 生成的,但我工作正常。 所有数据都被正确打印。 问题是当我想下订单时。 在@Controller 中,我无法从表单中看到变量。 这是 thymeleaf 的一部分代码
<tr th:each="cruise : ${cruises}">
<form method="post" th:action="@{/makeOrder}" th:object="${cruise}" name="formOrder" modelAttribute="cruise">
<td><span th:text="${cruise.nameOfCruise}" th:field="${cruise.nameOfCruise}"> nameOfCruise </span></td>
<td><span th:text="${cruise.id}" th:field="${cruise.id}"> id </span></td>
<td><span th:text="${cruise.date}"> date </span></td>
<td><span th:text="${cruise.cost}"> cost </span></td>
<td><span th:text="${cruise.route.startPlace}"> start </span></td>
<td><span th:text="${cruise.route.finishPlace}"> finish </span></td>
<td style="text-align: center;">
<span> Interested? </span>
<input type="submit" value="order">
</td>
</form>
</tr>
我尝试 PostMapping 方法
@PostMapping(value = "/makeOrder")
public String order(@ModelAttribute Cruise cruise, Model model){
logger.info(cruise.getNameOfCruise); //NULL
if(cruise == null) //NOT NULL. It doesn't execute
logger.info("Cruise is null);
...
}
我试过这种方式,但没有其他效果
public String order(@ModelAttribute("cruise") Cruise cruise, Model model)
实体 class
package com.zak.cruise.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.sql.Time;
import java.time.LocalDate;
@Entity
@Table(name = "cruise")
@Getter
@Setter
public class Cruise {
@Id
@Column(name = "idcruise")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name_of_cruise")
private String nameOfCruise;
@Column(name = "date")
private LocalDate date;
@Column(name = "time")
private Time time;
@Column(name = "cost")
private int cost;
@Column(name = "number_of_seats")
private int numberOfSeats;
@Column(name = "duration")
private int duration;
@ManyToOne
@JoinColumn(name = "route_id_route")
private Route route;
@ManyToOne
@JoinColumn(name = "ship_id_ship")
private Ship ship;
@Column(name = "description")
private String description;
public Cruise() {
}
public Cruise(String nameOfCruise, LocalDate date, Time time, int cost, int numberOfSeats, int duration, Route route, Ship ship, String description) {
this.nameOfCruise = nameOfCruise;
this.date = date;
this.time = time;
this.cost = cost;
this.numberOfSeats = numberOfSeats;
this.duration = duration;
this.route = route;
this.ship = ship;
this.description = description;
}
}
重要的巡航不是 NULL,而是实体 class。 我想知道的一切是如何从表单中提取变量以使用它们。 我指望你的帮助,提前谢谢你
Thymeleaf 仅进行渲染,它不会神奇地添加更多数据以形成基本 html 的帖子。 因此,不发布跨度元素,仅将输入元素发布到 controller。
因此,您要么必须将所有跨度元素更改为输入,要么可以添加带有 id 值的隐藏输入,并从 controller 的数据库中获取相应的 Cruise object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.