java—如何从模型属性访问公共字段

ryoqjall  于 2021-07-16  发布在  Java
关注(0)|答案(0)|浏览(222)

我需要用表单呈现html,我有以下html页面:

<form action="add" th:object="${form} method="post">
   <fieldset>
       <table>
           <tr th:each="book, itemStat : *{books}">
                <td><input th:field="*{books[__${itemStat.index}__].name}" />
           </tr>
       </table>
   </fieldset>
</form>

我有一个服务器端代码:

@GetMapping("/add")
public String addBook(Model model) {
    BooksForm form = new BooksForm();
    for(int i = 0; i < 3; i++) {
        form.books.add(new Book());
    }
    model.addAttribute("form", form);
    return "add_books";
}
public class Book {
    public int id;
    public String name;
}
public class BooksForm {
    public List<Book> books = new ArrayList<>();
}

但当我尝试运行此代码时,会出现如下异常:

org.springframework.beans.NotReadablePropertyException: Invalid property 'books[0]' of bean class [com.examples.model.BooksForm]: Bean property 'books[0]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:622) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.AbstractNestablePropertyAccessor.getNestedPropertyAccessor(AbstractNestablePropertyAccessor.java:839) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyAccessorForPropertyPath(AbstractNestablePropertyAccessor.java:816) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue

但如果我为我的公共财产添加getter public List<Book> books 一切正常。为什么没有getter我就不能得到这个属性?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题