Search code examples
spring-mvcthymeleaf

Thymeleaf: pass a parameter from the get form action in the url


I have a parameter in my controller and I want to get it back in the URL in a get form

I want to search in a list the objects by the agency but the problem is that thymeleaf gives me a fake URL, here is the example

here I will search with the keyword agency

<form th:action="@{lien(key=${key})}" method="get"> 
<input type="text" name="agence" th:value="${agence}" class="form-control"
                     placeholder=" Agence client..." />

and this is clientController :

@RequestMapping(value = "/lien")
public String droitUtilisateur(Model model,
        @RequestParam(name = "key", defaultValue = "0") int key, 
        @RequestParam(name = "page", defaultValue = "0") int p,
        @RequestParam(name = "size", defaultValue = "5") int s,
        @RequestParam(name = "agence", defaultValue = "") String agence) {
    String result = "";
    switch(key) {
    case 24421:
        Page<Client> pageClients = clientRepository.chercherParNom("%" + agence + "%", new PageRequest(p, s));
        model.addAttribute("listClient",pageClients.getContent()) ;
        int[] pages = new int[pageClients.getTotalPages()];
        model.addAttribute("pages", pages);
        model.addAttribute("pageCourante", p);
        model.addAttribute("size", s);
        model.addAttribute("key", key);
        model.addAttribute("agence", agence);
        result= key+"";
        break;

    }


    return result;
}

which returns this link :

http://localhost:6262/lien?agence=100

with this error

Template name cannot be null or empty

but it should be like this

http://localhost:6262/lien?key=24421&agence=100

Solution

  • You can't mix parameters in the url with parameters in form fields. You should add a hidden input for key:

    <form th:action="@{lien}" method="get"> 
        <input type="hidden" name="key" th:value="${key}" />
        <input type="text" name="agence" th:value="${agence}" class="form-control" placeholder=" Agence client..." />