Search code examples
javathymeleaf

Varargs in thymeleaf @ModelAttribute?


I want to pass multiple variable parameters (including none) for a @ModelAttribute evaluation from html thymeleaf page to a method:

//provide 0 or X params
@ModelAttribute("url")
public String url(String... params) {
    return "generatedurl";
}

The following thymeleaf statements should be possible:

th:href="@{${url()}"
th:href="@{${url('page')}}"
th:href="@{${url('page', 'sort')}}"

But it does not work. Why?


Solution

  • As a workaround: add the enclosing class as a model parameter, and call the method on this param from thymeleaf:

    @Controller
    public class PageController {
        @GetMapping
        public String persons(Model model) {
            model.addAttribute("util", this);
            return "persons";
        }
    
        public String url(String... params) {
            //evaluate...
            return "generatedurl";
        }
    }
    

    It's then possible to access the methods as normal:

    th:href="@{${url()}"
    th:href="@{${url('page')}}"
    th:href="@{${url('page', 'sort')}}"
    

    Only drawback is of course having to add the class to the model explicit.

    Another choice would be to initialize the model with the parameter permutations that I need. But that's less flexible:

    @ModelAttribute
    public void init(Model model) {
        model.addAttribute("plainUrl", ...);
        model.addAttribute("pageUrl", ...);
        model.addAttribute("pageSizeUrl", ...);
    }