A further improvement would be to have a model for a dropdown list that is not domain specific. This is especially useful when the whole form contains only dropdown lists. So this builds upon this article.
An element for a dropdown list consists of a label, the selected value and a list of the options:
public static class SelectElement{
private String label;
private String selected;
private Map<String, String> options;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSelected() {
return selected;
}
public void setSelected(String selected) {
this.selected = selected;
}
public Map<String, String> getOptions() {
return options;
}
public void setOptions(Map<String, String> options) {
this.options = options;
}
}
The actual model for this is a List of these objects as shown in the last article. The controller method then looks like this:
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String provide(ModelMap modelMap){
Random rand = new Random(System.nanoTime());
Map<String, String> country = new LinkedHashMap<String, String>();
country.put("CHINA", "China");
country.put("SG", "Singapore");
country.put("MY", "Malaysia");
country.put("US", "United Stated");
Map<String, String> javaSkill = new LinkedHashMap<String, String>();
javaSkill.put("Hibernate", "Hibernate");
javaSkill.put("Spring", "Spring");
javaSkill.put("Apache Wicket", "Apache Wicket");
javaSkill.put("Struts", "Struts");
List<String> l0 = new ArrayList<String>();
l0.add("China");
l0.add("Singapore");
l0.add("Malaysia");
l0.add("United Stated");
List<String> l2 = new ArrayList<String>();
l2.add("Hibernate");
l2.add("Spring");
l2.add("Apache Wicket");
l2.add("Struts");
List<SelectElement> l = new ArrayList<SelectElement>();
for (int i=0;i<4;i++){
SelectElement e = new SelectElement();
String skill = l0.get(rand.nextInt(4));
logger.debug("Country: "+skill);
e.setLabel("Country : ");
e.setSelected(skill);
e.setOptions(country);
l.add(e);
e = new SelectElement();
skill = l2.get(rand.nextInt(4));
e.setLabel("Java Skill : ");
e.setSelected(skill);
e.setOptions(javaSkill);
l.add(e);
}
SelectElementList l1 = new SelectElementList();
l1.setList(l);
modelMap.put("customerForm", l1);
return "config_test";
}
This makes the JSP pretty simple:
<form:form method="POST" commandName="customerForm" action="${link_url_home_config_test_save}">
<table>
<c:forEach items="${customerForm.list }" var="customer" varStatus="x">
<tr>
<td><c:out value="${customer.label }"/></td>
<td>
<form:select path="list[${x.index}].selected" items="${customer.options }">
</form:select>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>