【问题标题】:How to bind nested List object to JSP form?如何将嵌套列表对象绑定到 JSP 表单?
【发布时间】:2018-03-05 17:20:07
【问题描述】:

各位程序员们好,

我正在编写一个 Spring MVC 应用程序,供学生使用多项选择题进行在线评估。管理员应该能够创建评估,所以我创建了这个对象结构:

@Entity
@Table(name = "assessment")
public class Assessment {
    private List<Question> questions;
    // getter and setter
}


@Entity
@Table(name = "question")
public class Question {
    private String questionText;
    private List<Answer> answers;
    // getters and setters
}


@Entity
@Table(name = "answer")
public class Answer {
    private String answerText;
    private boolean isCorrect;
    // getters and setters
}

现在,我在管理页面上使用 JSP 表单:

控制器

@RequestMapping(value = "/add/assessment", method = RequestMethod.GET)
public String addAssessments(Model model) {
    model.addAttribute("assessmentModel", new Assessment());

    return "admin-assessments-create";
}

JSP 表单

<form:form method="POST" modelAttribute="assessmentModel">
    <form:input path="questions[0].questionText" type="text"/> <!-- this is working-->

    <form:radiobutton path="questions[0].answers[0].isCorrect"/> <!-- not working-->
    <form:input path="questions[0].answers[0].answerText"/>

    <button class="btn" type="submit">Submit</button>
</form:form>

当我转到此页面时,我收到以下错误:

org.springframework.beans.NotReadablePropertyException:
    Invalid property 'questions[0].answers[0].isCorrect' of bean class [com.johndoe.model.Question]:
    Bean property 'questions[0].answers[0].isCorrect' is not readable or has an invalid getter method:
    Does the return type of the getter match the parameter type of the setter?

我检查了所有的 getter 和 setter,但它们都很好。

问题:

如何避免NotReadablePropertyException 从而将嵌套的答案列表绑定到我的表单?

【问题讨论】:

    标签: java spring jpa data-binding


    【解决方案1】:

    使用

    <form:radiobutton path="questions[0].answers[0].correct"/>
    

    它会工作的。

    为什么?对于boolean 字段,您必须将get/set 范例调整为"is"XYZ()。对于 EL 表达式,您必须将“is”放在访问字段当前值的方法前面,几乎与使用“get”/“set”的方法相同”。

    【讨论】:

    • 所以问题根本不在于嵌套......这很尴尬。非常感谢。
    猜你喜欢
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    相关资源
    最近更新 更多