Thymeleaf模板和Spring Boot:从Java枚举创建单选输入 [英] Thymeleaf template and Spring Boot : Creating a radio input from Java enum
问题描述
我想从Java枚举类型源"中自动在Thymeleaf中填充无线电输入控件.我在后端使用Spring Boot.我的控制器初始化了枚举值的列表,如下所示:
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);
这至少在List方面有效(如我在日志输出中所见).
This works fine, at least as far as the List is concerned (as I can see in the log output).
然后,Thymeleaf模板尝试基于模型中的该属性实例化无线电控件,如下所示:
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
枚举非常简单:
public enum Source {
VALONE, VALTWO, VALTHREE, VALFOUR;
public String getName() {
return this.name();
}
}
这是我第一次与Thymeleaf合作,因此我认为这只是某个地方的简单语法问题,但是即使在谷歌搜索之后,我也找不到一个有效的示例.有任何想法吗?用枚举完全可以做到这一点吗?如果没有,哪种数据类型会更合适?
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?
非常感谢.欢呼声,
马丁
推荐答案
我玩了一些,然后开始工作了.以下HTML代码段基于Enums列表正确显示了单选按钮,并且还正确地连接到了模型,因为我在控制器的POST方法中收到了选定的值:
I played around a bit more and got it working. The following HTML snippet displays the radio buttons correctly based the list of Enums and also is wired to the model correctly, in that I received the selected value in the controller's POST method:
<div th:each="source : ${sources}">
<input name="source" type="radio" th:value="${source}"/><label for="source" th:text="| ${source} |">Something is wrong !</label>
</div>
有两个问题:
- 不需要访问枚举的name()属性(因此,使用$ {source}代替$ {source.name}很好)
- 代替th:field,使用输入控件的namne属性
非常感谢Periklis的评论.
Thanks a lot to Periklis for the comment.
这篇关于Thymeleaf模板和Spring Boot:从Java枚举创建单选输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!