Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Here is another code snippet doing something similar, in case it helps someone.

<s:iterator value="storageIds" var="sids">
    <s:hidden name="%{'storageIds[\\'' + key +'\\']'}" value="%{#sids.value}"/>
</s:iterator>

My action has a Map<String,String> named storageIds

When iterating a Map, key and value resolve to the Map.Entry properties.

Try This . Working perfectly for me

<s:iterator value="configMap" id="daa">
    <s:hidden name="%{'configMap[\\'' + key +'\\']'}" value="%{#daa.value}" />
</s:iterator>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top