【发布时间】:2018-06-12 14:25:13
【问题描述】:
我正在尝试将表单传递给控制器,但对象为空(看起来像是从默认构造函数而不是表单获取值)。不知道为什么@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>
【问题讨论】:
标签: spring model-view-controller kotlin thymeleaf