Spring表单命令可以是Map吗?


问题内容

Spring表单命令可以是Map吗?我通过扩展HashMap将命令设置为Map,并使用['property']表示法引用了属性,但没有用。

命令:

public class MyCommand extends HashMap<String, Object> {
}

HTML形式:

Name: <form:input path="['name']" />

结果错误:

org.springframework.beans.NotReadablePropertyException: Invalid property '[name]' of bean class [com.me.MyCommand]: Bean property '[name]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

这是不允许的,还是我的语法不正确?


问题答案:

Springn MVC命令需要使用JavaBeans来命名conventins(即getXXX()和setXXX()),因此,您不能为此使用映射。

一种选择是让一个具有单个Map属性的bean,即:

public class MyCommand {
  private final Map<String, Object> properties = new HashMap<String, Object>();

  public Map<String, Object> getProperties() { return properties; }
  // setter optional
}

然后,您可以执行以下操作(不确定语法的100%正确性,但有可能):

Name: <form:input path="properties['name']" />