我正在尝试将表单传递给控制器但对象是空的(看起来像从默认构造函数而不是表单获取值)。并且不知道为什么@Valid
不起作用。
码:
端点
@PostMapping("/add")
fun addDevice(@Valid @ModelAttribute device: Device, model: ModelMap): ModelAndView {
deviceRepository.save(device)
return ModelAndView("redirect:/devices/all", model)
}
实体:
@Entity
data class Device(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int? = null,
@NotNull
val name: String? = "",
@Min(10)
@Max(30)
val price: Int? = null,
@Size(min = 8)
val secretPhrase: String? = ""
) : Serializable
形成
<h1>Add Device</h1>
<!--/*@thymesVar id="device" type="com.example.demo.Device"*/-->
<form action="#" th:action="@{/devices/add}" th:object="${device}" th:method="post">
<div class="col-md-12">
<label>Name Cannot Be Null</label>
<input type="text" minlength="1" th:field="*{name}"></input>
</div>
<div class="col-md-12">
<label>Secret Phrase Min Length 8</label>
<input type="password" minlength="8" th:field="*{secretPhrase}"></input>
</div>
<div class="col-md-12">
<label>Price Between 10-30</label>
<input type="number" min="10" max="30" th:field="*{price}"></input>
</div>
<div class="col-md-12">
<input type="submit" value="Add"></input>
</div>
</form>
问题是你在数据类中使用val
而不是var
。
Spring MVC Thymeleaf调用实体类的no args构造函数(数据类总是有一个)。并且无法设置字段,因为它们是最终的。
用val
替换var
解决了这个问题。