java - 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
解决方案
我又玩了一会儿,让它工作了。以下 HTML 片段根据枚举列表正确显示单选按钮,并且正确连接到模型,因为我在控制器的 POST 方法中收到了选定的值:
<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 的评论。
推荐阅读
- python - Python网页抓取:来自谷歌搜索结果的网站
- html - exitBeforeEnter 没有按预期工作 - 页面转换出现问题
- apache-nifi - StandardRestrictedSSLContextService - 作为参数的 TrustStore 密码
- kubernetes - SolrCloud 时间路由别名架构
- python - 是否有非 UART python 传输协议层可以处理 512 字节或更少的 BLE 数据包?
- java - 如何在 Java 中居中对齐和格式化字符串
- json - 如何将多个参数从 JSON 导出到 AWS SSM 参数存储
- android - Kotlin/Android:无法使用 Canvas 将 LiveData 传递给 customView
- c++ - std::thread 成员对象在终止时崩溃
- sql-server - SQL Server 未正确更新数据