Views with Thymeleaf to create

Getting into Spring Boot, part 2 Views with Thymeleaf to create

In the first part of our series of Spring Boot, we have set up a project, and the Service is a first edition elicited. In this contribution it comes to Views, i.e. web pages that are created in Spring with Thymeleaf.

Companies

In the Spring of Views to be created, that is to say, the websites, with Thymeleaf.In the Spring of Views to be created, that is to say, the websites, with Thymeleaf.

(Image: Thymeleaf.org)

Thymeleaf is a server-side Template Engine, and is similar to that of the well-known Java Server Pages. Other than these Thymeleaf can be displayed-Templates with no problems but in the Browser, and with popular design tools can be edited.

Thymeleaf binds you, by you in the POM file of your Maven team project, Starter spring-boot-starter-thymeleaf as a dependency causes. In the Spring Tool Suite (STS) using the context menu (Spring > Edit a starter), or directly in the XML-Code to do:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

One of the most important Features of Spring Boot auto-configuration. Depending on included libraries, certain Beans are configured automatically. The Integration of spring-boot-starter-thymeleaf the configuration of a View causes resolver for Thymeleaf. This component maps View names to Thymeleaf Templates that can be searched under src/main/resources/templates.

Templates

Such a Template with the name “home.html” we have now with the following content:

<!DOCTYPE HTML>
<html xmlns_th="http://www.thymeleaf.org">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>   <p th_text="'Ich bin eine Thymeleaf-View!'" />
</body>
</html>

A note on Thymeleaf attribute “th:text only”, with the corresponding Namespace Declaration. As expected, it is used to output Text. You can load the HTML file with a Browser from the file system, not visible in the output, however. The Browser will ignore the unknown attribute “th:text”. Thymeleaf is a server-side Rendering technology. Unlike the client-side Rendering Frameworks like Angular or Vue.js it is essential to evaluate the instructions before Delivering to the Browser from the Server, and will be replaced.

The Template must be found by the Service, first of all, the Name must be communicated. This happens in the return value of a Controller method. Because the return value is used as key and find the Templates (and not, as in part 1, directly in the HTTP Response is to be written) is not required, the Annotation @responsebody. The File Extension “.html“ is assumed as the Default and can be omitted:

@Controllerpublic class PersonController {   @GetMapping("https://www.dev-insider.de/")
public String home() {
return "home";
}
}

The call to http://localhost:8080 in the Browser now displays desired website with the Text.

Data transfer via Model

To make the View a bit more interesting, to get data from the Controller to pass. Here the passed object is a Person:

package com.example.demo;public class Person {   private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}

To Transfer the parameter list of the method gets an implicit Model object is added. This Model will be managed by Spring Boot, it will automatically be passed to the View more. The Model any kind of data can be added to objects. Later, the data such as last name and first name to be loaded, of course, from a database, here you will be encoded but now it’s time tough.

@Controllerpublic class PersonController {   @GetMapping("https://www.dev-insider.de/")
public String home(Model model) {
      Person person = new Person();
person.setFirstname("Max");
person.setLastname("Mustermann");
model.addAttribute(person);
      return "home";
}
}

In the Thymeleaf Template on the Person object in the Model with the help of the dollar sign and curly braces can be accessed.

   <span th_text="${person.firstname}" />
<span th_text="${person.lastname}" />

This also works with lists. When a List object is stored with a plurality of persons in the Model, with “th:each” about to iterate:

<tbody>
<tr th_each="person: ${personList}">
<td th_text="${person.firstname}" />
<td th_text="${person.lastname}" />
</tr>
</tbody>

The addAttribute () method of the Models can alternatively be used as the second Parameter, the Name of the object, pass it in the Template should be addressed. If you omit it, it will use the lowercase Name of the class, in the case of lists with an attached List (i.e. in person, or person-of-list).

Forms

So far, data has been transferred from the Service to the website. This also works in the other direction, for example, is to be transferred in a form to input data to the Service. The following piece of Code gives an example:

<h1>Name</h1>
<form action="https://www.dev-insider.de/views-mit-thymeleaf-erstellen-a-976811/#" th_action="@{/}" th_object="${person}" method="post">
<p>Vorname: <input type="text" th_field="*{firstname}" /></p>
<p>Nachname: <input type="text" th_field="*{lastname}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>

Form with Thymeleaf attributes.Form with Thymeleaf attributes.

(Image: Dr. Koller)

The Thymeleaf attribute “th:action” specifies the URL to be called. With “th:object” is specified, the object in the Model on the variables and then in the further course, with “th:field” is accessed.

Since the Request is a Post, comes on the server side, in a further method, the Annotation @post-mapping to use. Post Requests to / be processed in this method. The list of methods arguments will be expanded to the specified Person. The Annotation @model attributes before it causes the Argument is retrieved from the model.

@PostMapping("https://www.dev-insider.de/")public String home(@ModelAttribute Person person, Model model) {   model.addAttribute(person);
return "home";
}

At this point, it is important to be mindful of the expiration of the Requests. If you call in the Browser localhost:8080, as this is a GET Request that is processed by the Controller method with the GetMapping. In it, the Person John DOE is generated and the Model is Packed.

Thereafter, it is determined by the View Resolver to the appropriate View with the form, and the Model is filled. If you click on the form, the Submit Button will run a Post Request, and passes the name you entered in the post-mapping annotated Controller method. First name and last name are there in the Person object.

Thymeleaf offers much more, of course, we have only scratched the surface. Often th:if A is required, for example, to show or Hide HTML elements under certain conditions. For more information on this and many other attributes can be found in the documentation for the Thymeleaf project.

In the next part of the series we deal with databases and Spring Boot. Until then!

(ID:46970305)

Ready to see us in action:

More To Explore

IWanta.tech
Logo
Enable registration in settings - general
Have any project in mind?

Contact us:

small_c_popup.png