Search code examples
springthymeleafpath-variables

Thymeleaf + Spring how to pass to a controller a @PathVariable from a form select option value


I would like to use a select box to redirect to an URL containing the select value.

Here bellow the HTML page with thymeleaf variables :

<form th:action="@{/app/}">
    <select id="app" name="app">
        <option th:each="app : ${apps}"
            th:value="${app.id}"
            th:text ="${app.name}">
        </option>
    </select>
    <button>Go</button>
</form>

The controller is written as following :

@RequestMapping("/app/{appId}")
public ModelAndView getApp(@PathVariable String appId){...}

My goal is to access the controller with the URL : mydomain/app/{app.id}/ I tried to use th:field onto the select without success. I'm missing something here.

Please, could you explain me how to add the select value to the URL expected by the controller ?

Thank you for the hints

EDIT following @NicolaiEhemann answer

I moved to javascript using jquery and ajax :

$('button').click(function() {
    $.ajax({
        url: '/app/' + $('#app').val(),
        dataType: 'html'
    }).done(function(data) {
        $('#result').html(data)
    });
});

Thank you.


Solution

  • Thymeleaf will only generate static html code. To achieve what you want, you have to write client side javascript to handle the 'input' event event to change the form action when a different value is selected, or handle the form 'submit' event to override the default action of the form submission. The relevant js code will probably be dependent on which framework you use.