【发布时间】:2018-05-01 00:14:04
【问题描述】:
我在一个列表中有多个对象,并且想为该列表中的每个对象创建一个表单(用户一次只能提交一个对象)。但是,一旦我使用 th:field 而不是 name 和 value,我就会遇到异常。也许有人可以帮助我。它仅在使用 th:each; 时发生如果我将单个对象传递给它的工作形式......我将问题减少到最低限度,因此它更具可读性:)
例外:
java.lang.IllegalStateException: Bean 名称 'o' 的 BindingResult 和普通目标对象都不能用作请求属性
控制器类:
@Controller
public class TestController {
@GetMapping("/objectlisttest")
public ModelAndView getObjectListTest() {
ModelAndView mv = new ModelAndView("objectlisttest");
List<DataObject> objects = new ArrayList<>();
for (int i = 0; i < 5; i++) {
DataObject o = new DataObject();
o.setText("Dataobject");
objects.add(o);
}
mv.addObject("objects", objects);
return mv;
}
@PostMapping("/objectlisttest")
public ModelAndView editObjectListTest(DataObject o, BindingResult br) {
System.out.println(o);
return getObjectListTest();
}
public static class DataObject {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
}
查看:
<div th:each="o : ${objects}">
<form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
<label>Text<input type="text" th:field="*{text}"></label>
<input type="submit">
</form>
</div>
提前致谢
编辑: 将视图更改为
<div th:each="o : ${objects}">
<form th:object="${o}" th:action="@{/objectlisttest}" method="POST">
<label>Text<input type="text" th:value="*{text}" th:name="text"></label>
<input type="submit">
</form>
</div>
有效。但是 th:field 会好很多...
【问题讨论】:
-
嘿,我面临着类似的问题。你能解决这个问题吗?
-
事实是,我切换到在前端使用角度。我认为它可以提供比任何类型的服务器端渲染更好的用户体验。一开始需要多一点时间,但以后会有回报。