How can I get values from several selected checkboxes and send them as a List to the Spring MVC?

0

Alright? I'm having a question, I'm developing a system using Spring MVC and HTML 5 in View, and as a renderer I'm using thymeleaf.

I'm trying to get all the selected values from a checkbox set that represent the days of the week: Monday, Tuesday through Friday and would like to know how do I get all the values of these checked checkboxes and send them as a List to my controller? Below the View code:

<div class="col-sm-4" >
     <label class="checkbox-inline" th:each="dia : ${todosDiaDaSemana}" >
            <input type="checkbox" th:value="${dia.nome}" th:text="${dia.nome}" name="dias" />
    </label>
</div>

Below is the entity Class:

@Entity
@Table(name = "turma")
public class Turma {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(length = 80, nullable = false)
private String nome;

@Column(length = 6)
private String horarioInicial;

@Column(length = 6)
private String horarioFinal;

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<DiaDaSemana> dias = new ArrayList<>();

@Enumerated(EnumType.STRING)
@Column(length = 15, nullable = false)
private Escolaridade escolaridade;

@Enumerated(EnumType.STRING)
@Column(length = 20, nullable = false)
private Disciplina disciplina;

// methods getters and setters
...
}

Below is the entity DiaDaSemana:

@Entity
@Table(name = "dia_da_semana")
public class DiaDaSemana {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NaturalId
@Column(length = 7, nullable = false)
private String nome;

// methods getters and setters
...
}
    
asked by anonymous 24.01.2017 / 21:13

1 answer

1

Just use the @RequestParam annotation and enter the parameter name, which in your case is the value of the name field in input type="checkbox" .

//Altere o value e method de acordo com o necessário
@RequestMapping(value="caminhoDoMeuFomulario", method=RequestMethod.POST)
public String form(@RequestParam("dias") List<String> dias) {
        //aqui você faz o processamento que quiser
    return "seujsp";
}

If you want to make the most of what Thymeleaf can do, take a look this integration tutorial between it and Spring MVC. There is a complete example that includes what you want and much more!

Edit:

In your case it does not work because you want to bind an object to a checkbox . For you to do this, you must implement org.springframework.core.convert.converter.Converter . Because of the way you've mapped your entities, implementing this interface might not be the best option, you'd better change your mapping a bit. I'll show you both options and choose the one that best suits you.

Changing Mapping:

As the days of the week are a constant, you could turn them into an enumeration. It would look like this:

DiaDaSemana

public enum DiaDaSemana {
    DOMINGO("Domingo"),
    SEGUNDA_FEIRA("Segunda-feira"),
    TERCA_FEIRA("Terça-feira"),
    QUARTA_FEIRA("Quarta-feira"),
    QUINTA_FEIRA("Quinta-feira"),
    SEXTA_FEIRA("Sexta-feira"),
    SABADO("Sábado");

    private final String nome;

    private DiaDaSemana(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }
}

Your class Turma would look like this:

@Entity
@Table(name = "turma")
public class Turma {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ElementCollection(targetClass=DiaDaSemana.class)
    @CollectionTable(name="turma_diaDaSemana")
    @Enumerated(EnumType.STRING)
    @Column(name="dia", nullable=false)
    private Set<DiaDaSemana> diasDaSemana;

    // Seus outros atributos
    // methods getters and setters
}
To get all the values of the enumeration, just call the View method:

<div class="col-sm-4" >
    <label class="checkbox-inline" th:each="dia : ${todosDiaDaSemana}" >
        <input type="checkbox" th:value="${dia}" th:text="${dia.nome}" name="diasDaSemana" />
    </label>
</div>

On your todosDiasDaSemana :

//Altere o value e method de acordo com o necessário
@RequestMapping(value="caminhoDoMeuFomulario", method=RequestMethod.POST)
public String form(Turma turma) {
        //aqui você faz o processamento que quiser
    return "seujsp";
}

Implementing a Converter:

DiaDaSemanaConverter:

import org.springframework.core.convert.converter.Converter;

public class DiaDaSemanaConverter implements Converter <String, DiaDaSemana> {

    @Override
       public DiaDaSemana convert(String source) {
        return new DiaDaSemana(source);
    }
}

Register% s of% in Spring:

@EnableWebMvc
@Configuration
@ComponentSca
public class SpringFrameworkConfig extends WebMvcConfigurerAdapter{

    //Os outros métodos

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DiaDaSemanaConverter());
        super.addFormatters(registry);
    }
}

Your View (the value of the DiaDaSemana.values() attribute must be the same as your setter without the prefix "set", example: if your method is called Controller the DiaDaSemanaConverter attribute must be name ): / p>

<div class="col-sm-4" >
    <label class="checkbox-inline" th:each="dia : ${todosDiaDaSemana}" >
        <input type="checkbox" th:value="${dia.nome}" th:text="${dia.nome}" name="diasDaSemana" />
    </label>
</div>

On your setDiasDaSemana :

//Altere o value e method de acordo com o necessário
@RequestMapping(value="caminhoDoMeuFomulario", method=RequestMethod.POST)
public String form(Turma turma) {
        //aqui você faz o processamento que quiser
    return "seujsp";
}
    
24.01.2017 / 23:58