Search code examples
javaspringspring-mvcjakarta-eefreemarker

Spring MVC HashMap Form Integration


I have a hash map in model object. How to bind the hash map when form submission.

Map<String, List<Employee>> employeeMap= new HashMap< String, List<Employee>>(); 
List<Employee> employeeList;
//getters and setters of employeeMap and employeeList

the Employee Object is

class Employee{

String name;
String pincode;
String organization;

//getters and setter

}

the form input value is

List{ //list iteration here

<input type="text" name="employeeMap[${emp.id}].employeeList[list_index].name" value=""/>
}

but it didn't work. please help me how to give the proper input name for binding with the hash map


Solution

  • In my opinion you have two mistakes:

    1. Your map has key as String but your ${emp.id} is probably int or long, try use quotes.
    2. In map you have list of employees, this list can't have a name, you can just remove it.

    Try like this:

    <input type="text" name="employeeMap["${emp.id}"][list_index].name" value=""/>
    

    Here is my similar working example:

        User u1 = new User();
        u1.setEmailAddress("email1");
        User u2 = new User();
        u2.setEmailAddress("email2");
    
        u1List.add(u1);
        u1List.add(u2);
        u2List.add(u2);
        u2List.add(u1);
    
        userMap.put("1", u1List);
        userMap.put("2", u2List);
    
        model.addAttribute("userMap", userMap);
    

    JSP:

    Email of second user from map with key=1 = ${employeeMap["1"][1].emailAddress}