Spring guide (learn about view templates)

Keywords: Java Thymeleaf JSP Spring FreeMarker

Understanding view templates

Model view controller (MVC) software design pattern is a method used to separate concerns in software applications. In principle, application logic or controller is separated from technology used to display information to users or view layers. This model is a communication tool between controller and view layers.

Within an application, the view layer can use one or more different technologies to render views. Spring's Web-based applications support various view options, commonly known as view templates, which are described as "templates" because they provide a markup language for exposing model properties in views during server-side rendering.

View template library

The following view template libraries are Spring compatible:

Comparison between JSP and Thymeleaf

The following example shows how to render the same content using JSP and the Thymeleaf template.

JSP

Note the JSTL (JavaServer web page Standard Tag Library) expression.

<c:url var="hotelsUrl" value="/hotels"/>
<form:form modelAttribute="searchCriteria" action="${hotelsUrl}" method="get" cssClass="inline">
    <span class="errors span-18">
        <form:errors path="*"/>
    </span>
    <fieldset>
        <div class="span-8">
            <label for="searchString">SeaString:</label>
            <form:input id="searchString" path="searchString"/>
        </div>
        ...
    </fieldset>
</form:form>

Thymeleaf

In this example, tags are integrated with standard HTML.

<form action="#" th:object="${searchCriteria}" th:action="@{/hotels}" method="get" class="inline">
    <ul th:if="${#fields.hasErrors('*')}" class="errors span-18">
        <li th:each="err : ${#fields.errors('*')}" th:text="${err}">Input is incorrect</li>
    </ul>
    <fieldset>
        <div class="span-8">
            <label for="searchString">Search String:</label>
            <input type="text" id="searchString" th:field="*{searchString}" />
        </div>
        ...
    </fieldset>
</form>

Posted by cdherold on Tue, 03 Dec 2019 15:56:18 -0800