java Spring 中的命令对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1429760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:31:51  来源:igfitidea点击:

Command Objects in Spring

javaspringspring-mvc

提问by Jeune

I have a command object composed of primitive fields and an object field. How do I bind my form fields to the fields in the object?

我有一个由原始字段和对象字段组成的命令对象。如何将表单字段绑定到对象中的字段?

I tried doing this but to no avail

我尝试这样做但无济于事

<form:form commandName="course" method="POST">
     <form:input path="activity.activity"/>
         .
         .
         .
</form:form>

I get this error

我收到这个错误

org.springframework.beans.NotReadablePropertyException: 
      Invalid property 'course' of bean class

My Command class is like this

我的命令类是这样的

public class Course {
    private long id;
    private String owner;
    private String title;
    private List<LearningActivity> activity = new ArrayList<LearningActivity>();

    //getters and setters
}

public class LearningActivity {
private long ID;
private String activity;
    private String link;

    //getters and setters
}

采纳答案by Jacob Mattison

Your list either needs to be pre-populated with as many LearningActivity objects as you plan to refer to (using activity[0], activity[1], etc.) or it needs to be a lazy list. A lazy list is a list that will populate itself with empty objects when a given index is referenced.

您的列表要么需要预先填充您计划引用的尽可能多的 LearningActivity 对象(使用活动 [0]、活动 [1] 等),要么需要是一个惰性列表。惰性列表是一个列表,当引用给定索引时,它将用空对象填充自身。

A comment indicates that you're trying to use Apache Commons LazyList, which ought to work -- are you missing an import directive? However, as an alternative there is a Spring lazy list implementation called AutoPopulatingList.

一条评论表明您正在尝试使用 Apache Commons LazyList,它应该可以工作——您是否缺少导入指令?但是,作为替代方案,有一个名为 AutoPopulatingList 的 Spring 惰性列表实现。

回答by ChssPly76

Two possible issues here:

这里有两个可能的问题:

  1. activity.activityis invalid (unless your getters do not correspond to your member variables) because Course.activityis a list. You need to address a particular list element - e.g. activity[0].activity. You'll also have to make sure it actually exists.

  2. Have you configured your FormController correctly? Does it pass Courseinstance to view as it should? Take a look at Spring MVC tutorialfor an example.

  1. activity.activity无效(除非您的 getter 与您的成员变量不对应),因为Course.activity是一个列表。您需要解决特定的列表元素 - 例如activity[0].activity。您还必须确保它确实存在。

  2. 您是否正确配置了 FormController?它是否通过Course实例进行查看?以Spring MVC 教程为例。

If after you've fixed #1 and verified that #2 is done correctly the error doesn't go away, please post more details (FormController mapping / source).

如果在您修复 #1 并验证 #2 正确完成后,错误没有消失,请发布更多详细信息(FormController 映射/源代码)。