Search code examples
spring-bootthymeleafspring-thymeleaf

Thymeleaf syntax for the form action


I have this form:

<body>
<h1>Fill out the form</h1>
<form action="@{/submit}" method="post" th:object="${person}">
    <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="error"></span>

    <label for="name">Person Name:</label>
    <input type="text" id="name" th:field="*{name}" />
    <br />

    <label for="orgName">Organization:</label>
    <input type="text" id="orgName" th:field="*{orgName}" />
    <br />

    <label for="email">Email:</label>
    <input type="email" id="email" th:field="*{email}" />
    <br />

    <label for="telephone">Telephone:</label>
    <input type="tel" id="telephone" th:field="*{phone}" />
    <br />

    <button type="submit">Submit</button>
</form>
</body>

</html>

but I see this on the browser:

enter image description here


Solution

  • You need to use th:action tag instead of action tag. And also specify the th namespace in html tag.

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
      <head>
      </head>
      <body>
        <h1>Fill out the form</h1>
        <form th:action="@{/submit}" method="post" th:object="${person}">
            <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="error"></span>
        
            <label for="name">Person Name:</label>
            <input type="text" id="name" th:field="*{name}" />
            <br />
        
            <label for="orgName">Organization:</label>
            <input type="text" id="orgName" th:field="*{orgName}" />
            <br />
        
            <label for="email">Email:</label>
            <input type="email" id="email" th:field="*{email}" />
            <br />
        
            <label for="telephone">Telephone:</label>
            <input type="tel" id="telephone" th:field="*{phone}" />
            <br />
        
            <button type="submit">Submit</button>
        </form>
      </body>
    </html>
    

    Checkout Details on Thymeleaf Form