How to bind a Checkbox to an Object List in Spring MVC

1

Next, I have a question about handling a Checkboxes list. I have a list of objects that are the Courses, and I would like this list to be linked to a 'List' of another class as follows:

You are in the JSP

<ul><form:checkboxes element="li" path="aluno.cursos" itemValue="id" itemLabel="nome" items="${cursoList}"></form:checkboxes></ul>

Class to link to

@Document(collection = "alunos")
public class Aluno {
...
private List<Curso> cursos;
...
public List<Curso> getCursos() {
    return cursos;
}

public void setCursos(List<Curso> cursos) {
    this.cursos = cursos;
}
...

In my controller the function is as follows:

public ModelAndView registered(@ModelAttribute("aluno") Aluno aluno, BindingResult result, HttpServletRequest request) {
    System.out.println("Registrando: " + aluno.toString());
    ...
}

At this point, I see that the list of courses in the student class should be set, but it is NULL What is the correct way for me to link this list of Checkboxes to my Student class list?

    
asked by anonymous 11.03.2014 / 20:02

1 answer

1

Your code looks correct, so the problem should be somewhere else.

Probably the problem is that the equals() and hashCode methods need to be implemented in the Curso class.

Note that when HTML is rendered on the screen, checkboxes "lose" the information of the original object, having only id as value. When the form is submitted back to the server, Spring receives the% s of% s selected and needs to find the corresponding objects to add to the final list specified in the id attribute.

    
12.03.2014 / 20:42