I want to populate a map property on a Struts2 action from a JSP. What is the format of the data names that I should use? Initially I am interested in populating a Map<String, String> but in the future I would be interesting in populating a Map<String, DomainClass> where the DomainClass has properties of its own.
I have an action, with a property as follows -
private Map<String,String> assetProps;
...
public Map<String, String> getAssetProps() {
return assetProps;
}
public void setAssetProps(Map<String, String> assetProps) {
this.assetProps = assetProps;
}
To set values onto the map, there are basically two steps. First off, OGNL can't instantiate the map, so it is up to you. In my action, I implement the Preparable interface, but instantiate it before running the 'public String input()' method as follows -
public class EditAction extends ActionSupport implements Preparable {
...
public void prepare() {
// just satisfying Preparable interface so we can have prepareInput()
}
public void prepareInput() throws Exception {
assetProps = new HashMap<String,String>();
}
Now, the object is non-null, I can use syntax similar to the following in the JSP -
<s:iterator value="asset.properties" var="prop">
<sjx:textfield name="%{'assetProps[\\'' +#prop.propName +'\\']'}"
value="%{#prop.propValue}"
label="%{#prop.propName}" size="25"/>
</s:iterator>
The iterator pulls a set of objects off the stack and iterates over it. The important part is the "name=" section, notice the double-escaped single quotes. That way, when the page renders, the name of the input element becomes (for example) - assetProps['Screen Size']. When the page is submitted, inside the "public void execute()" method, assetProps is fully populated.