Eclipse or SUNrise...

Eclipse or SUNrise...
...JAVA for sure

Sunday, June 24, 2007

LabelValueBean from Struts

Yesterday I was modyfing a simple struts form. The modification was to add a pulldown box with status names stored in database. The status list had to be obtained from a dictrionary table and consisted from Integer type index and String type status name. On this occasion I have found a nice LabelValueBean object which comes with standard struts utilites. You can find it under org.apache.struts.util package.

So what is special about it? I guess there is nothing special, but it enables us to produce a nice, readable code, plus you don't have to make a special pojo objects or make magic tricks after which you need extra time to understand what is going on in the code each time you look at it. So, how does the bean help. The LabelValueBean consists of two Strings, one for the Label (status name) and one for the Id (ie. status id in the dictionary). To make it running you need two things on the struts form, and that is:

private Integer statusId; // for selected id
private List statusList; // for all the status values and names

// plus proper geters and seters of course...


In the action, in the initialization section you just need to fill the List of statusList with values from the database or whatever you need

And finally in the frontend layer - the jsp level, you code like that:

<html:select property="statusId">
<html:optionsCollection property="statusList" value="value" label="label"/>
</html:select>


As simple as that - I especially like the code in jsp because it is nice and clear and it is really easy to understand for someone who didn't wrote it himself. The String id stored in the value will be automaticaly casted to Integer type of statusId property. This one shows once again the beauty of struts - it just makes the worst work for you. I love the fact that struts is object oriented and that it is cappable of using Collections.

No comments: