Java Springboot从thymeleaf选项获取对象
因此,我试图用Springboot和Thymeleaf创建一个新的产品对象。我将类别列表传递到thymeleaf中,并将它们显示在创建对象时要选择的选项选择中。问题是正在创建对象,但类别为空,我不知道为什么 这是我的产品实例变量Java Springboot从thymeleaf选项获取对象,java,spring-boot,spring-mvc,thymeleaf,Java,Spring Boot,Spring Mvc,Thymeleaf,因此,我试图用Springboot和Thymeleaf创建一个新的产品对象。我将类别列表传递到thymeleaf中,并将它们显示在创建对象时要选择的选项选择中。问题是正在创建对象,但类别为空,我不知道为什么 这是我的产品实例变量 public class Product { @Id private String id; private String name, description; private double price; private Binar
public class Product {
@Id
private String id;
private String name, description;
private double price;
private Binary image;
private Category category;
private ProductStatus status;
public Product() {
}
它有一个Category的实例变量
@Document(collection = "categories")
public class Category {
@Id
private String id;
private String name, description;
public Category() {
}
这是创建产品选项的thymeleaf代码,其中包含类别。
和控制器
m.addObject(“产品”,新产品())代码>
它接受@Valid产品
当我试图打印出我选择的类别名称时,我会得到一个NPE
我正在尝试从选项th:value=“${cat}”
但它不起作用。您需要将对象添加到模型和视图中:
modelAndView.getModelMap().addAttribute("dto", dto);
把它放在胸腺侧,例如:
<form th:action="@{/url}" th:object="${dto}" th:method="post">
<input type="date" th:field="${dto.date}">
简短的回答。将
中的th:value=“${cat}”更改为th:value=“${cat.id}”
。原因是您正在th:value=“${cat}”
中指定类别对象的引用值,该值将不再存在于内存中。由于spring会自动将id转换为相应的对象,所以我们只需将id分配给值category=1
将转换为new category()
,其中id=1
封装了我所拥有的表单。在控制器中,我有一个m.addObject(“product”,new product());使用modelAndView.getModelMap().addAttribute(
modelAndView.getModelMap().addAttribute("dto", dto);
<form th:action="@{/url}" th:object="${dto}" th:method="post">
<input type="date" th:field="${dto.date}">
@Valid DtoClass dtoClass