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

时间:2021-03-18 14:14:25

标签: java spring spring-boot spring-mvc thymeleaf

我需要用表单呈现 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

但是如果我为我的公共财产 public List<Book> books 添加 getter 一切正常。 为什么没有 getter 就无法获得此属性?

0 个答案:

没有答案
相关问题