列表中每个对象的百里香叶形式会导致"Neither BindingResult nor plain target object"



>我在一个列表中有多个对象,并希望为该列表中的每个对象创建一个表单(用户一次只能提交一个对象(。但是一旦我使用 th:field 而不是名称和值,我就会得到一个异常。也许有人可以帮助我。它仅在使用 th:each 时发生;如果我将单个对象传递给它工作的形式......我将问题减少到最低限度,使其更具可读性:)

例外:

java.lang.IllegalStateException:BindingResult 和 Bean name 'o' 的纯目标对象都不能用作请求属性

控制器类:

@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>

工程。但是:田野会更好...

它期望在模型中具有"o"对象。如果您致电

mv.addObject("o", someObject);

我认为错误消失了,但模型中的"o"和作为循环变量的"o"之间存在冲突。

我会说添加多个具有相同模型引用的表单不是好主意(所有表单都有th:object="${o}"(。

您应该重新设计逻辑。要么将每个对象单独放置在模型中,要么只创建一个表单来保留列表。

相关内容

最新更新