Spring boot Thymeleaf:从表单中获取对象

Spring boot Thymeleaf:从表单中获取对象,spring-boot,thymeleaf,Spring Boot,Thymeleaf,假设我有一个实体: @Entity @Table(name = "Building") @Data public class Building { @Id @Column(name = "buildingId") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer buildingId; @OneToOne(cascade = {CascadeType.MERGE} @JoinColumn(name = "b

假设我有一个实体:

@Entity
@Table(name = "Building")
@Data
public class Building {

@Id
@Column(name = "buildingId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer buildingId;

@OneToOne(cascade = {CascadeType.MERGE}
@JoinColumn(name = "buildingType")
private BuildingType buildingType;
 //...

}
在控制器中,我将所有建筑类型放入模型中:

@RequestMapping("/addBuilding")
    public String newBuilding(Model model, @ModelAttribute Building building){
       model.addAttribute("buildingTypes", buildingTypeService.getBuildingTypes()); //gives me an ArrayList<BuildingType>
}

有可能从Thymeleaf获取对象吗?或者是否有必要为BuildingType创建一个基本的瞬态字段(例如字符串),从Thymeleaf返回,并根据此字段在controller中搜索BuildingType?

从客户端开始,Thymeleaf不存在(客户端,您的控制器)。Thymeleaf是一个模板引擎。现在,Spring(而不是thymeleaf)允许您在控制器中接收对象的方式基于html元素的名称。因此,如果有一个输入名为“x”,另一个输入名为“y”,并且在控制器中映射一个具有x和y属性的对象,则该对象将被填充。另一方面,thymeleaf的“th:field”基本上设置了处理html时输入的名称
<form class="some-form" method="post" th:action="@{/addBuilding}">
    <select id="type" class="some-class" required>
        <option th:each="buildingType : ${buildingTypes}" th:text="${buildingType.name}"></option>
    </select>
    <button type="submit" class="button">Store</butto>
</form>
<form class="some-form" method="post" th:action="@{/addBuilding}" th:object="${building}">
        <select id="type" class="some-class" th:field="*{buildingType}" required>
            <option th:each="buildingType : ${buildingTypes}" th:value="${buildingType}" th:text="${buildingType.name}"></option>
        </select>
        <button type="submit" class="button">Store</button>
</form>
@RequestMapping("/addBuilding")
        public String newBuilding(Model model, @ModelAttribute Building building){
           //...
           System.out.println((building.getBuildingType() instanceof BuildingType)); //false
    }