views:

1333

answers:

2

Can a Spring form command be a Map? I made my command a Map by extending HashMap and referenced the properties using the ['property'] notation but it didn't work.

Command:

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

HTML form:

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

Results in the error:

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?

Is this not allowed or do I have incorrect syntax?

+1  A: 

Springn MVC commands need to use JavaBeans naming conventins (ie getXXX() and setXXX()) so no you can't use a map for that.

One alternative is to have a bean with a single Map property ie:

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

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

Then you can do something like this (not 100% sure on the syntax but it is possible):

Name: <form:input path="properties['name']" />
cletus
Your sintaxis is correct, but map properties don't get actually bound. The problem is the code generated is something like <input name="propertiesName" value="valueAppearsOk"/>. So, when you submit this form, nothing puts the correct value in properties.
Sinuhe
A: 

Yes it can but... You need to reference it as <form:input path="name[index].key|value"/> e.g.

<form:input path="name[0].value"/>

What's the 0 or index for?
Steve Kuo