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

Asked

Viewed 467 times

0

I have a question about Spring MVC.

I’m developing a system using HTML5 in View, and as a renderer I am using the thymeleaf.

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

1 answer

0

Class: Product

List: Addresses

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

You can use a Ubmit in your view, which takes the necessary parameters for your address list and takes it 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;

   ...
}

Browser other questions tagged

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