Spring MVC Thymeleaf Kotlin

标签 spring model-view-controller kotlin thymeleaf

我试图将表单传递给 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/

相关文章:

iphone - 将手势识别器/ Action 方法附加到 View 会违反 Model View Controller 吗?

c# - 如何在 Post 中返回 MVC2 中的 JSON 结果

PHP 单独的管理 Controller CODEIGNITER

java - 设置Spring security后无法再访问jsp

java - Spring 和 Hibernate 的重复关键问题 - 需要帮助

java - 如何使用 View 解析器返回移动或普通 View ?

Java bean 获取属性名称而不是值

kotlin -::property.isInitialized 无法区分同名的方法和属性

android - Kotlin 继承 - 没有为参数上下文传递值

gradle - 如何在多个 Gradle 项目之间共享样板 Kotlin 配置?