How to handle multiple inputs with the same name in Java?

Asked

Viewed 222 times

3

How do I manipulate in the back-end using multiple Java input's with the same name?

For example:

    <input type='text' name='telefone' ><br>
    <input type='text' name='telefone' ><br>
    <input type='text' name='telefone' ><br>
    <input type='text' name='telefone' >

I tried to receive in the method parameter as a array(String[] telefone) but it didn’t work. I tried to put also the [] in the name but it didn’t work either.

Ps: I’m using the Springmvc.

  • Marcos, welcome to Stack Overflow. Take a look at "How to ask a good question?" and "MVCE". Post the relevant part of the form (including action, etc.) as well as the relevant pieces of your backend (controller, etc.). In general we solve this type of problem using a List as @ModelAttribute and names numbered in the view (e. g, telefone[0], telefone[1], etc), but it is difficult to give you advice without knowing the code in more detail.

1 answer

1


I will take into account that you are sending this data to the backend using form-data, if that is so, you can receive a List phones in your controllers, and spring will give bind to you, however your inputs should follow a notation similar to an array, something like:

    <input type='text' name='telefone[0]' ><br>
    <input type='text' name='telefone[1]' ><br>
    <input type='text' name='telefone[2]' ><br>
    <input type='text' name='telefone[3]' >

On your controller:

    public void salvaTelefones(List<String> telefones) {
      //faz algo.
    }

Browser other questions tagged

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