How to retrieve data from a th:value (thymeleaf) in the controller?

Viewed 550

I need to retrieve in a Spring MVC controller the content that comes from a th:value field in the view. Tried the code below using RequestParam but didn't work.

Form code:

<form action="form1" method="post">
<input type="text" th:value="${personId}"/>
<input type="submit" name="btnSubmit" value="Submit">
</form>

Spring MVC Controller

@RequestMapping(value="/form1", params = "btnSubmit", method = RequestMethod.POST)
public String formMethod (@RequestParam("personId") int personId) {
    return "";
}

Note: I know this can also be achieved replacing th:value by th:field, adding a th:object in the form tag and using a @ModelAttribute in the controller. But that would require creating a whole object and tighting the form to the object. Don't want to do that. Want something simpler with just one field leaving the form to bind to another object. So, would like to know if it's possible to retrive that data when it's a th:value (or something else that would work with a single field as well).

1 Answers

You don't need to use th:value to return data to controller. You need to configurate the th:object in your tag form:

<form action="form1" method="post" th:object="${person}">

Then you change the th:value to name = "personId" :

<input type="text" name="personId" />

In the controller you need to change the parameters method:

@RequestMapping(value="/form1", params = "btnSubmit", method = RequestMethod.POST)
public String formMethod (@Valid Person person, Model Model) {
    return "";
}

Obs.: If you have more submit's button in your html page, you can use params = "btnSubmit=Submit".

Learning more: https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

Related