【问题标题】:Thymeleaf template and Spring Boot : Creating a radio input from Java enumThymeleaf 模板和 Spring Boot:从 Java 枚举创建无线电输入
【发布时间】:2019-04-07 01:50:11
【问题描述】:

我想从名为“source”的 Java 枚举类型自动填充 Thymeleaf 中的单选输入控件。我在后端使用 Spring Boot。 我的控制器初始化一个枚举值列表,如下所示:

this.sourcesAsList = Arrays.asList(Source.values());
model.addAttribute("sources", sourcesAsList);

这很好用,至少就列表而言(正如我在日志输出中看到的那样)。

Thymeleaf 模板然后尝试根据模型中的此属性实例化一个单选控件,如下所示:

<div th:each="source : ${sources}">
  <input type="radio" th:field="*{source}"  th:value="${source.value}"/><label th:text="| ${source.value} |">Should not see this !</label>
</div>

但是,当我尝试加载此页面时,我收到以下错误:

[Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/feedbackapp2.html]")] with root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'source' available as request attribute

枚举非常简单:

public enum Source {
    VALONE, VALTWO, VALTHREE, VALFOUR;

    public String getName() {
        return this.name();
    }
}

这是我第一次使用 Thymeleaf,所以我猜这只是某个地方的一个简单的语法问题,但即使在谷歌搜索之后我也找不到一个工作示例。有任何想法吗?有可能用枚举做到这一点吗?如果不是,哪种数据类型更合适?

非常感谢。 干杯,

马丁

【问题讨论】:

  • 问题是 th:field="*{source}"。可能你没有这样的属性。能否请您发布您的html页面的代码(feedbackapp2.html)?

标签: java spring-boot enums radio-button thymeleaf


【解决方案1】:

我又玩了一会儿,然后它就开始工作了。以下 HTML sn-p 根据枚举列表正确显示单选按钮,并且也正确连接到模型,因为我在控制器的 POST 方法中收到了选定的值:

<div th:each="source : ${sources}">
  <input name="source" type="radio" th:value="${source}"/><label for="source" th:text="| &nbsp; ${source} |">Something is wrong !</label>
</div>

有两个问题:

  • 不必访问枚举的 name() 属性(因此, 使用 ${source} 而不是 ${source.name} 很好)
  • 使用输入控件的 namne 属性代替 th:field

非常感谢 Periklis 的评论。

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2016-01-26
    • 2020-10-07
    • 2017-03-08
    • 2021-01-23
    • 2017-08-24
    • 2017-06-21
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多