首页 > 解决方案 > Thymeleaf template and Spring Boot : Creating a radio input from Java enum

问题描述

I would like to populate a radio input control in a Thymeleaf automatically from a Java enum type called "source". I am using Spring Boot in the backend. My controller initialises a list of the enum values like this:

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

This works fine, at least as far as the List is concerned (as I can see in the log output).

The Thymeleaf template then tries to instantiate a radio control based on this attribute in the model, like so:

<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>

However, when I try to load this page, I get the following error:

[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

The enum is pretty simple:

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

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

It's the first time I work with Thymeleaf, so I guess it is just a simple syntax problem somewhere, but even after googling I couldn't find a working example. Any ideas? Is it possible at all to do this with an enum? If not, what kind of datatype would be more appropriate?

Thanks a lot. Cheers,

Martin

标签: javaspring-bootenumsradio-buttonthymeleaf

解决方案


我又玩了一会儿,让它工作了。以下 HTML 片段根据枚举列表正确显示单选按钮,并且正确连接到模型,因为我在控制器的 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} 很好)
  • 代替 th:field,使用输入控件的 namne 属性

非常感谢 Periklis 的评论。


推荐阅读