Search code examples
springspring-bootthymeleafspring-form

Thymeleaf forms vs Spring MVC Forms?


Here are 2 different forms, one - with Spring MVC forms, another - with Thymeleaf. But what is the difference, which one should I use?

Spring Forms

  <form:form methid="POST" action="/showDetails" modelAttribute="employee">
    Name <form:input path="name"/>
    Surname <form:input path="surname"/>
    Salary <form:input path="salary"/>
    <input type="submit" value="OK">
    </form:form>

Thymeleaf

<form action="#" th:action="@{/register}" method="post" th:object="${user}">
        <label>Full name:</label>
        <input type="text" th:field="*{name}" /><br/>
 
        <label>E-mail:</label>
        <input type="text" th:field="*{email}" /><br/>
 
        <label>Password:</label>
        <input type="password" th:field="*{password}" /><br/>
 
        <label>Birthday (yyyy-mm-dd):</label>
        <input type="text" th:field="*{birthday}" /><br/>
 
        <label>Gender:</label>
        <input type="radio" th:field="*{gender}" value="Male" />Male
        <input type="radio" th:field="*{gender}" value="Female" />Female<br/>
  
 
 
        <button type="submit">Register</button>    
    </form>

Solution

  • This SpringMVC Form is similar to HTML. In SpringMVC <form:form> tag plays an important role here; it’s very similar to the regular HTML tag but the modelAttribute attribute is the key which specifies a name of the model object that backs this form:

    <form:form method="POST" 
      action="/SpringMVC/addEmp" modelAttribute="emp">
    

    This will correspond to the @ModelAttribute later on in the controller. Whereas,

    Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS, and text.

    You can read more about it :- thvsjsp