java - 如何将嵌套List对象绑定(bind)到JSP表单?

标签 java spring jpa data-binding

各位程序员大家好,

我正在为学生编写一个 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 表单:

Controller

@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 并将嵌套答案列表绑定(bind)到我的表单?

最佳答案

使用

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

它会起作用的。

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

关于java - 如何将嵌套List对象绑定(bind)到JSP表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116058/

相关文章:

java - SpringBoot 将数据存储在 h2 中,但无法检索数据并在浏览器或 postman 中以 JSON 格式显示

java - Parse + Robolectric 导致 java.lang.VerifyError : Bad type on operand stack

Java : Convert from doc to pdf and ppt to pdf failing

java - 随机化大写字母

java - 使用或不使用 Eclipse 生成 Spring SP 类

java - Spring应用程序-将键/值保留到属性文件而不转义

java - java中的这些注释会抛出什么异常?

JavaScript 调用并将参数发送到 JNLP 文件

java - 在 Spring Batch 中将值动态替换为配置 xml 文件中的占位符

java - 用于查询内存中数据的 JPA