Multiple select with Spring MVC - codecentric AG Blog

:

During our coding night (there’s be a separate blog for it), we committed ourselves to use only Spring technologies. But a simple requirement had a rather dramatic effect.

Update (2011-11-10): With Spring 3.0 things will be a lot easier, take a look at the comment from Antti Andreimann for details.

How do you create a multiple select box with Spring MVC? You should be able to select multiple elements, which then get added to a collection of the backing bean.

We are implementing a simple time tracking application. The domain model contains projects, which can have staff members assigned. Projects have tasks, which also have staff members assigned to. So in the task creation view we need a select box that contains all available employees.

Model

Here are the most important extracts from Tasks and Staff members:

Task

@Entity
public class Task implements Serializable {
	@Id
	@GeneratedValue
	private long id;
 
	@ManyToMany
	private Set<Staff> staffs = new HashSet<Staff>(0);
 
	//...
}

@Entity public class Task implements Serializable { @Id @GeneratedValue private long id;@ManyToMany private Set<Staff> staffs = new HashSet<Staff>(0);//... }

Staff

@NamedQuery(name = "staff.activeStaff", query = "select s from Staff s where s.disabled = false")
@Entity
@DiscriminatorValue("STAFF")
public class Staff extends Person {
 
	//...
}

@NamedQuery(name = "staff.activeStaff", query = "select s from Staff s where s.disabled = false") @Entity @DiscriminatorValue("STAFF") public class Staff extends Person {//... }

Person

@NamedQuery(name = "person.findByUsername", query = "from Person p where p.login.username = :username")
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public abstract class Person implements Serializable {
 
	@Id
	@GeneratedValue
	private long id;
 
	//...
}

@NamedQuery(name = "person.findByUsername", query = "from Person p where p.login.username = :username") @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING) public abstract class Person implements Serializable {@Id @GeneratedValue private long id;//... }

View

In the task creation view, we need a select box that shows all available employees. The selected employees shall then be assigned to the task when the form is submitted.

@Controller
@SessionAttributes("project")
public class ProjectController {
	@RequestMapping(method = RequestMethod.GET, value = "/project/createTask.action")
	public void createTaskView(@ModelAttribute Task task, Model model) {
		List<Staff> activeStaff = timetrackingService.getActiveStaff();
		model.addAttribute("activeStaff", activeStaff);
	}
 
	//...

@Controller @SessionAttributes("project") public class ProjectController { @RequestMapping(method = RequestMethod.GET, value = "/project/createTask.action") public void createTaskView(@ModelAttribute Task task, Model model) { List<Staff> activeStaff = timetrackingService.getActiveStaff(); model.addAttribute("activeStaff", activeStaff); }//...

The JSP that belongs to the controller contains this snippet for the select box:

<td><label for="staffs">Chose Staff: </label></td>
<td><form:select path="staffs" multiple="true" items="${activeStaff}" itemLabel="fullName" itemValue="id"/></td>
<td><form:errors path="staffs" /></td>

<td><label for="staffs">Chose Staff: </label></td> <td><form:select path="staffs" multiple="true" items="${activeStaff}" itemLabel="fullName" itemValue="id"/></td> <td><form:errors path="staffs" /></td>

The problem is, as soon as you submit the form, you will get a ServletRequestBindingException, because Spring has no idea how to map a String (or String[] when multiple staff members have been selected) to a Set.

org.springframework.web.bind.ServletRequestBindingException: Errors binding onto object 'task'; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'task' on field 'staffs': rejected value [3]; codes [typeMismatch.task.staffs,typeMismatch.staffs,typeMismatch.java.util.Set,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [task.staffs,staffs]; arguments []; default message [staffs]]; default message [Failed to convert property value of type [java.lang.String] to required type [java.util.Set] for property 'staffs'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [de.codecentric.timetracking.model.Staff] for property 'staffs[0]': no matching editors or conversion strategy found]

org.springframework.web.bind.ServletRequestBindingException: Errors binding onto object 'task'; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'task' on field 'staffs': rejected value [3]; codes [typeMismatch.task.staffs,typeMismatch.staffs,typeMismatch.java.util.Set,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [task.staffs,staffs]; arguments []; default message [staffs]]; default message [Failed to convert property value of type [java.lang.String] to required type [java.util.Set] for property 'staffs'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [de.codecentric.timetracking.model.Staff] for property 'staffs[0]': no matching editors or conversion strategy found]

Additionally, the generated HTML is missing the ID for staff members!

<select id="staffs" multiple="multiple" name="staffs">
<option value="">firstname lastname</option>
<option value="">aaaa aaaa</option>
<option value="">firstname lastName</option>
<option value="">firstname aaaa</option>
<option value="">firstname lastname</option>
</select>
<input type="hidden" value="1" name="_staffs"/>

<select id="staffs" multiple="multiple" name="staffs"> <option value="">firstname lastname</option> <option value="">aaaa aaaa</option> <option value="">firstname lastName</option> <option value="">firstname aaaa</option> <option value="">firstname lastname</option> </select> <input type="hidden" value="1" name="_staffs"/>

Id as String

In order to have the staff member ID in the value attribute of the option element, we can create a new getter in the Person class that returns the id as String, and then use that in the JSP:

public abstract class Person implements Serializable {
	//...
	public String getIdAsString() {
		return new Long(id).toString();
	}
}

public abstract class Person implements Serializable { //... public String getIdAsString() { return new Long(id).toString(); } }

<form:select path="staffs" itemValue="idAsString" multiple="true" items="${activeStaff}" itemLabel="fullName"/>

<form:select path="staffs" itemValue="idAsString" multiple="true" items="${activeStaff}" itemLabel="fullName"/>

InitBinder

The solution to the binding problem is more difficult. We need a PropertyEditor for the attribute ‘staffs’. Spring contains a number of PropertyEditors, so we can use the CustomCollectionEditor. It is expected that the property editor can map the string from options value back to the element, so we need to store that mapping somewhere, in a map for example.

public class ProjectController {
 
private Map<String, Staff> staffCache;
 
@RequestMapping(method = RequestMethod.GET, value = "/project/createTask.action")
public void createTaskView(@ModelAttribute Task task, Model model) {
	List<Staff> activeStaff = timetrackingService.getActiveStaff();
	staffCache = new HashMap<String, Staff>();
	for (Staff staff : activeStaff) {
		staffCache.put(staff.getIdAsString(), staff);
	}
	model.addAttribute("activeStaff", activeStaff);
}
 
@InitBinder
protected void initBinder(WebDataBinder binder) throws Exception {
	binder.registerCustomEditor(Set.class, "staffs", new CustomCollectionEditor(Set.class) {
		protected Object convertElement(Object element) {
			if (element instanceof Staff) {
				System.out.println("Converting from Staff to Staff: " + element);
				return element;
			}
			if (element instanceof String) {
				Staff staff = staffCache.get(element);
				System.out.println("Looking up staff for id " + element + ": " + staff);
				return staff;
			}
			System.out.println("Don't know what to do with: " + element);
			return null;
		}
	});
}

public class ProjectController {private Map<String, Staff> staffCache;@RequestMapping(method = RequestMethod.GET, value = "/project/createTask.action") public void createTaskView(@ModelAttribute Task task, Model model) { List<Staff> activeStaff = timetrackingService.getActiveStaff(); staffCache = new HashMap<String, Staff>(); for (Staff staff : activeStaff) { staffCache.put(staff.getIdAsString(), staff); } model.addAttribute("activeStaff", activeStaff); }@InitBinder protected void initBinder(WebDataBinder binder) throws Exception { binder.registerCustomEditor(Set.class, "staffs", new CustomCollectionEditor(Set.class) { protected Object convertElement(Object element) { if (element instanceof Staff) { System.out.println("Converting from Staff to Staff: " + element); return element; } if (element instanceof String) { Staff staff = staffCache.get(element); System.out.println("Looking up staff for id " + element + ": " + staff); return staff; } System.out.println("Don't know what to do with: " + element); return null; } }); }

The code still contains some debug output to System.out, which has to be removed. But it shows that the method is called very frequently. Only for showing the select box with 5 employees, the method is caller 15 times. 10 times the id is passed in as a String, and 5 times the object is passed in. I have found no good documentation what exact behaviour is expected from that PropertyEditor, this is the best working solution I could come up with.

Looking up staff for id 1: Staff(firstname lastname)
Looking up staff for id 1: Staff(firstname lastname)
Converting from Staff to Staff: Staff(firstname lastname)
Looking up staff for id 2: Staff(aaaa aaaa)
Looking up staff for id 2: Staff(aaaa aaaa)
Converting from Staff to Staff: Staff(aaaa aaaa)
Looking up staff for id 3: Staff(firstname lastName)
Looking up staff for id 3: Staff(firstname lastName)
Converting from Staff to Staff: Staff(firstname lastName)
Looking up staff for id 4: Staff(firstname aaaa)
Looking up staff for id 4: Staff(firstname aaaa)
Converting from Staff to Staff: Staff(firstname aaaa)
Looking up staff for id 5: Staff(firstname lastname)
Looking up staff for id 5: Staff(firstname lastname)
Converting from Staff to Staff: Staff(firstname lastname)

Looking up staff for id 1: Staff(firstname lastname) Looking up staff for id 1: Staff(firstname lastname) Converting from Staff to Staff: Staff(firstname lastname) Looking up staff for id 2: Staff(aaaa aaaa) Looking up staff for id 2: Staff(aaaa aaaa) Converting from Staff to Staff: Staff(aaaa aaaa) Looking up staff for id 3: Staff(firstname lastName) Looking up staff for id 3: Staff(firstname lastName) Converting from Staff to Staff: Staff(firstname lastName) Looking up staff for id 4: Staff(firstname aaaa) Looking up staff for id 4: Staff(firstname aaaa) Converting from Staff to Staff: Staff(firstname aaaa) Looking up staff for id 5: Staff(firstname lastname) Looking up staff for id 5: Staff(firstname lastname) Converting from Staff to Staff: Staff(firstname lastname)

After selecting an employee and submitting the form, expectedly there’s only one line in the log, converting the id back to the staff member.:

Looking up staff for id 3: Staff(firstname lastName)

Looking up staff for id 3: Staff(firstname lastName)

Conclusion

With the massive amount of web frameworks around, I find it surprisingly complicated to achieve something as simple as a multiple select box in Spring MVC. But, I just leard Spring MVC yesterday, so I might not know all details yet. So if there’s a more elegant and simpler solution to achieve the same as described above, I very much welcome your feedback.