How can I add objects to a list dynamically through views?

0

I have a question regarding Spring MVC .

I'm developing a system using HTML5 in View , and as a renderer I'm using thymeleaf .

For example, if I have a class Produto , and it has a list of Endereços , is there a way for me to add in the list, considering that springmvc is framework action based ?

    
asked by anonymous 07.04.2016 / 03:26

1 answer

0
  

Class: Product

     

List: Addresses

     

Goal: Add an item to the list through the view.

You can use a submit in your view, which takes the required parameters to your address list and takes you to your method, for example:

View code:

<form th:action="@{/produtos/addEndereco}" th:object="${endereco}" method="POST">
        <input type="text" placeholder="Logradouro"
                th:field="*{logradouro}"/> 
        <input type="number" placeholder="numero" th:field="*{numero}"/>
        <button type="submit">Adicionar</button>
</form>

In your controller, you will call the method that adds an item to the list.

Controller:

        @Controller
        @RequestMapping("/produtos")
        public class ProdutosController{

           @Autowired
           Produtos produtos;

           @RequestMapping(value="/addEndereco",method = RequestMethod.POST)
           public String adicionarEndereco(Endereco endereco){
               this.produtos.addEndereco(endereco);
               return "redirect:/produtos";
           }
        }

Model:

@Service
public class Produtos {

   private static List<Endereco> enderecos = new ArrayList<>();

   public void addEndereco(Endereco endereco){
      enderecos.add(endereco);
   }
}

And your address bean:

public class Endereco {

   String logradouro;
   int numero;

   ...
}
    
03.06.2016 / 18:10