kosmičák kosmičák -4 years ago 169
Java Question

OGNL Array and List Indexing

I'm sending this parameter to my struts action


In my action I'm interested in the index and the value.
I defined a getter/setter pair for
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.
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.

Answer Source

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" />

    <input type="submit" name="submit" value="submit"/>

Gets populated without a issue

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download