How can I take values from selected checkboxes and send as a List to Spring MVC?

Asked

Viewed 1,115 times

0

All right? I’m having a doubt, I’m developing a system using Spring MVC and HTML 5 in View,e como renderizador estou utilizando o Thymeleaf.

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

<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 follows 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 follows 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
...
}
  • What is "day"? A class that represents the days of the week, a String, something else?

  • I have an Entity class that has a List<Diadasemana> attribute and another Entity Diadasemana, as follows: @Onetomany(fetch = Fetchtype.EAGER, Scade = Cascadetype.ALL) private List<Diadasemana> days = new Arraylist<>();

  • Edit your question and add the class DiaDaSemana please.

  • It is already edited.

1 answer

1


Just use the annotation @RequestParam and enter the name of the parameter, which in its case is the field value name in the 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";
}

In case you want to take better advantage of what Thymeleaf can do, take a look in that integration tutorial between it and Spring MVC. There is a complete example that includes what you want and more!


Edit:

In your case it’s not right because you want to link an object to a checkbox. For you to do this, you must implement a org.springframework.core.convert.converter.Converter. Due to the way you mapped your entities, implementing this interface may not be the best option, it would be better to change your mapping a little. I’ll show you both options and you choose the one you think best.

Changing the Map:

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
}

Your View(don’t forget to change todosDiasDaSemana for it to reflect the enumeration values. To obtain all the enumeration values just call the method DiaDaSemana.values()):

<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>

In his Controller:

//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 the being DiaDaSemanaConverter 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 attribute name must be the same as your Setter without the prefix "set", example: if your method is called setDiasDaSemana the attribute name must be diasDaSemana):

<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>

In his Controller:

//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";
}
  • In my case, I would like to save the Class object and automatically convert all fields to attributes of it, but when I put this extra parameter says that it could not convert an array of Strings to the correct value of the attribute.

  • @Osmaeldesousabraga I edited the answer and added possible solutions to your problem.

  • Thank you so much for your help, I’m starting now on web development with Spring and have a lot to learn yet, but with help from people like you that the community moves on. Vlw, hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.