【发布时间】:2018-09-02 21:43:47
【问题描述】:
我是 Thymeleaf 的新手,也许这是一个简单的问题。请帮助我。谢谢。
控制器代码:
@Controller
public class TestController {
@GetMapping(value = "/")
public String testget(Map<String, Object> model) {
TestBean bean = new TestBean();
List<Person> list = new ArrayList<>();
for (int index = 1; index < 5; index++) {
Person p = new Person();
p.setId(index);
p.setName("name" + index);
list.add(p);
}
model.put("allList", "nothing");
bean.setList(list);
model.put("testbean", bean);
return "NewFile";
}
@PostMapping(value = "/")
public String testpost(Map<String, Object> model//
, @ModelAttribute(name = "testbean") TestBean bean) {
List<Person> list = bean.getList();
model.put("bean", bean);
model.put("allList", list.toString());
return "NewFile";
}}
简单的映射器和一个 Person bean:
@Data
public class TestBean {
private List<Person> list;
}
@Data
public class Person {
private int id;
private String name;
}
HTML 代码:
<form action="#" th:action="@{/}" th:object="${testbean}" method="post">
<p th:text="'ALL : ' + ${allList}"></p>
<table>
<tr th:each="person : ${testbean.list}">
<td>Id:<input type="text" th:value="${person.id}"
/></td>
<td>name: <input type="text" th:value="${person.name}" /></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
我想将列表放到页面上并更改属性以刷新。 但我不知道如何添加 th:field 标签,我尝试添加
**th:field="*{testbean.list[__${index}__].id}"**
但它失败了:
Invalid property 'testbean' of bean class [com.TestBean]
更新1
我试过了
th:field="*{list[__${index}__].id}"
我在添加 th:field
的位置出现错误Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (NewFile:14)] with root cause
java.lang.NumberFormatException: For input string: "null"
我的问题是我能做些什么,我可以在控制器中获得 List。
【问题讨论】:
-
尝试
th:field="*{list[__${index}__].id}不带testbean如果您使用*表示法,那么它将引用父对象。 -
谢谢你的帮助。我也试过了。另一个 [error For input string: "null"] Servlet.service() for servlet [dispatcherServlet] 在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 org.thymeleaf.exceptions.TemplateProcessingException: 在执行处理器 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (NewFile:14)] 时出错,根本原因
-
添加任何变量“rowStat”以循环保持状态索引
th:each="person,rowStat : ${testbean.list}"并像th:field="*{list[__${rowStat.index}__].id}一样访问它 -
太棒了,现在可以正常工作了,非常感谢。
标签: spring-boot thymeleaf