我试图将表单传递给 Controller ,但对象是空的(看起来像是从默认构造函数而不是表单获取值)。不知道为什么 @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 调用实体类的无参数构造函数(数据类总是有一个)。 并且无法设置这些字段,因为它们是最终的。
只需将 val
替换为 var
即可解决问题。
关于Spring MVC Thymeleaf Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48068452/