Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OGNL Array and List Indexing

Tags:

java

struts2

ognl

I'm sending this parameter to my struts action

cdata[1]=bar

In my action I'm interested in the index and the value. I defined a getter/setter pair for CDATA as the OGNL documentation suggests:

public void setCdata(int index, String value){
    LOG.info("setData; key="+ key +"; value="+ value);
    // store index and value;
}

public String getCdata(int index){
    return null; // don't really need a setter
}

This is the Exception I get:

2013-04-29 15:38:49,792 [http-apr-8080-exec-3] WARN  com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn(CommonsLogger.java:60) - Error setting expression 'cdata[1]' with value '[Ljava.
lang.String;@4223d2a4'
ognl.OgnlException: target is null for setProperty(null, "1", [Ljava.lang.String;@4223d2a4)
        at ognl.OgnlRuntime.setProperty(OgnlRuntime.java:2309)
        at ognl.ASTProperty.setValueBody(ASTProperty.java:127)
        at ognl.SimpleNode.evaluateSetValueBody(SimpleNode.java:220)
        at ognl.SimpleNode.setValue(SimpleNode.java:301)
        at ognl.ASTChain.setValueBody(ASTChain.java:227)
        at ognl.SimpleNode.evaluateSetValueBody(SimpleNode.java:220)
        at ognl.SimpleNode.setValue(SimpleNode.java:301)
        at ognl.Ognl.setValue(Ognl.java:737)
        ...

If I define a public member variable String[] cdata = new String[1000] I don't see any exception in my log but my setter is not called either. If the member variable is private I get another exception again.

like image 701
kosmičák Avatar asked Oct 22 '22 11:10

kosmičák


1 Answers

Use the following setup

List<String> cdata = new ArrayList<String>();

public List<String> getCdata() {
   return cdata;
}

public void setCdata(final List<String> cdata) {
    if (cdata == null) {
        this.cdata = new ArrayList<String>();
    } else {
        this.cdata = cdata;
    }
}

submit the values from JSP like cdata[1]=value etc

only requirement is to have the getters/setters. I've tested this Tomcat7 running on java 1.6. You can submit values like cdata[0], cdata[1] likewise

or else you could use a map

private Map<String, String> data = new HashMap<String, String>();

public Map<String, String> getData() {
    return data;
}

public void setData(Map<String, String> data) {
    this.data = data;
}

JSP can have

<s:form action="indexProperty">

    <h3>Test The Map</h3>
    <input type="text" name="data['0']"/>
    <input type="text" name="data['1']"/>

    <s:iterator value="data.entrySet()" var="aData">
        <s:property value="#aData.key" />-<s:property value="#aData.value" />
    </s:iterator>

    <input type="submit" name="submit" value="submit"/>
</s:form>

Gets populated without a issue

like image 98
Dev Blanked Avatar answered Oct 24 '22 11:10

Dev Blanked