【问题标题】:Spring MVC Thymeleaf KotlinSpring MVC Thymeleaf Kotlin
【发布时间】: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


    【解决方案1】:

    问题是您在数据类中使用val 而不是var

    Spring MVC Thymeleaf 调用实体类的无参数构造函数(数据类总是有一个)。 并且无法设置字段,因为它们是最终的。

    只需将val 替换为var 即可解决问题。

    【讨论】:

    • 谢谢!绝对应该在文档中的某处注明。
    猜你喜欢
    • 2018-01-07
    • 2019-06-28
    • 2021-11-19
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2017-06-17
    相关资源
    最近更新 更多