Thymeleaf Form Action Example

By Arvind Rai, April 12, 2023
On this page, we will learn to use form action with Thymeleaf. Find the attributes to create a form using Thymeleaf.
th:action : Specifies action URL for form submit. Use @{...} expression to specify URL. To resolve variables, use ${...} expression.
th:placeholder : Specifies placeholder for an input field. To resolve variables, use ${...} expression.
th:value : Specifies the value of submit button or any input fields. To resolve variables, use ${...} expression.

Using th:action

The th:action is used to specify an action URL that will hit on form submit. Find the code to use th:action with Thymeleaf variables.
<form th:action="@{${myPage.formAction}}">
    <input type="text" name="name" th:placeholder="${myPage.nameVal}"/><br/>
    <input type="text" name="age" th:placeholder="${myPage.ageVal}" />
    <input type="submit" value="Submit" th:value="${myPage.submitValue}"/>
</form> 
Output
<form action="saveData">
    <input type="text" name="name" placeholder="Name"/><br/>
    <input type="text" name="age" placeholder="Age" />
    <input type="submit" value="Submit"/>
</form> 
The th:action can directly be assigned with hardcoded URL.
<form th:action="@{saveData}">
 ------
</form> 

Using th:attr

We can specify form action using th:attr too. In this case action, placeholder and value will be specified as following.
<form th:attr="action=@{saveData}">
    <input type="text" name="name" th:attr="placeholder=${myPage.nameVal}"/><br/>
    <input type="text" name="age" th:attr="placeholder=${myPage.ageVal}" />
    <input type="submit" th:attr="value=${myPage.submitValue}"/>
</form> 
Output
<form action="saveData"<
    <input type="text" name="name" placeholder="Name"/<<br/<
    <input type="text" name="age" placeholder="Age" /<
    <input type="submit" value="Submit"/<
</form< 
The hardcoded Action URL can directly be assigned as following.
<form th:attr="action=@{saveData}">
   ------
</form> 
Find the print screen of the output.
Thymeleaf Form Action Example

Reference

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE







©2024 concretepage.com | Privacy Policy | Contact Us