Monday, January 12, 2009

Spring, Velocity and Dropdown List

Here is how I put a dropdown list, e.g. groups, on one of my Spring, Velocity web applications.

First, the key word is springFormSingleSelect. In my velocity file, I wrote

#springFormSingleSelect("command.group", ${groups}, "style='width:270px;'")

Second, use referenceData to populate values in the "groups" in the Controller class.

referenceData(...) {
Map model ...
... add (key, value) into a Map called groups
model.put("groups", groups);
return model;
}

Third, create a custom property editor, GroupEditor extends PropertyEditorSupport and override the setAsText method.

Note the Spring Framework will pass you the groupId and you need to create a Group object from the groupId, then call setValue(group).

Fourth, register the GroupEditor in the initBinder method.

binder.registerCustomerEditor(Group.class, new GroupEditor());

You may find the groups data will disappear after onSubmit. Don't worry, there is an easy fix. Instead of return a new ModelAndView, return showForm(request, response, errors, model). You can put whatever you need into the "model".

I spent a full weekend to sort everything out. Hope it can help you.

2 comments:

Anonymous said...

Its is neccesaary to create a editor ?

Tom :L said...

Good question. It is necessary.