Monday, October 6, 2008

Struts 2 Multibox

I've had a lot of experience with Struts 1.x and decided it was time to move on to the newer Struts 2 framework. I have found much of the documentaion helpful, but there was one thing that I got hung up on. That thing was: what happened to the tag? It was obvious to me that the functionality had to be available in Struts 2, but where was it?

I had limited success with the tag, but it would always fail validation if none of the options were selected. This made no sense to me since selection one or more of the checkboxes would return exactly what I expected, an array of Longs. In my action I had my results defined as:

private Long[] valueArray;

The problem was that the Interceptor that the conversion interceptor was generating an error when no values were selected. The reason this was happening was due to the fact that instead of returning an empty array or even null, Struts now returns "false" by default. This meant that valueArray[0] == "false" which obviously cannot be converted to a number.

Here's how I overcame the multibox functionality:

JSP Code:

<s:iterator status="rowStatus" value="orderList">
<tr>
<td>
<s:checkbox fieldvalue="%{orderId}" name="valueArray">
</td>
<td>
<s:property value="orderName">
</td>
</tr>
</s:iterator>

Action Code:

private List valueArray;

public String execute() throws Exception
{
long[] longArray = asLongArraySafe(valueArray);

// Do something with the longArray.

}

// This method will create an array that contains only the numeric values.
public long[] asIntArraySafe(List list)
{
long[] results = new long[0];
ArrayList parsedValueList = new ArrayList();
if(list != null && list.size() > 0)
{
for(String valueString : list)
{
try
{
parsedValueList.add(new Long(valueString));
}catch(Exception e){}
}

results = new long[parsedValueList.size()];
int x = 0;
for(Long value : parsedValueList)
{
results[x++] = value.longValue();
}
}
return results;
}

1 comment:

Unknown said...

According to Stanford Medical, It is in fact the one and ONLY reason women in this country live 10 years more and weigh an average of 19 kilos lighter than we do.

(And actually, it is not about genetics or some secret exercise and EVERYTHING to do with "how" they eat.)

P.S, I said "HOW", not "what"...

Tap on this link to reveal if this short quiz can help you decipher your true weight loss possibilities