我想从名为“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,所以我想这只是某个地方的一个简单的语法问题,但即使在谷歌搜索后我也找不到一个有效的示例。有任何想法吗?有可能用枚举来做到这一点吗?如果不是,哪种数据类型更合适?
非常感谢。 干杯,
马丁
<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="..."
与表单一起使用,如 thymeleaf 文档中所述:
https://www.thymeleaf.org/doc/tutorials/3.1/ thymeleafspring.html#creating-a-form虽然文档没有明确提到“enum”,而且我找不到任何其他有关它的文档,但它似乎有效。 MyEnumType.java:
public enum MyEnumType {
CHOISE_ONE,
CHOISE_TWO;
}
public class MyForm {
private MyEnumType myEnum;
// getter + setter methods
...
public String getHandler(Model model) {
...
model.addAttribute("myForm", MyForm);
...
@PostMapping("/gothere")
public String postHandler(@ModelAttribute MyForm myForm) {
MyEnumType theChoice = myForm.getMyEnum();
...
<form id="myform" method="post" th:action="@{/gothere}" th:object="${myForm}" th:with="myEnumTypeClass=${T(de.example.MyEnumType)}">
<input id="radio-button-choice-one" type="radio" th:field="*{myEnum}" th:value="${myEnumTypeClass.CHOISE_ONE}">
<input id="radio-button-choice-two" type="radio" th:field="*{myEnum}" th:value="${myEnumTypeClass.CHOISE_TWO}">
...