Although now slowly in popular separation development before and after the end, but the scene learned that there are some companies doing before and after the end of development, regardless of the development of in front and back end, we will need the back-end page template (in fact, even before and after the separation, also can in some situations need to use the page template, such as email templates).

The use of Velocity as a page template was also supported in early Spring Boot. Now It is no longer supported in Spring Boot, and page templates mainly support Thymeleaf and Freemarker. Spring Boot also supports Jsp, the most basic page template in Java, but it is a bit more cumbersome to use.

Songo plans to introduce each of the three page templating techniques in three articles.

Today we mainly look at Thymeleaf integration in Spring Boot!

Thymeleaf profile

Thymeleaf is a next-generation Java templating engine that is similar to traditional Java templating engines such as Velocity and FreeMarker, but unlike traditional Java templating engines, Thymeleaf supports HTML prototyping.

It allows front-end engineers to directly open the browser to view the style, and also allows back-end engineers to view the display effect with real data. At the same time, SpringBoot provides Thymeleaf automatic configuration solution, so it is very convenient to use Thymeleaf in SpringBoot.

In fact, Thymeleaf can be rendered as an HTML fragment in addition to displaying basic HTML and rendering the page. For example, we can use Thymeleaf as the template for sending emails.

In addition, because the Thymeleaf template suffix is.html, it can be opened directly by the browser, so it is very convenient to preview.

integration

  • Create a project

It is very easy to integrate Thymeleaf in Spring Boot, just add Thymeleaf when creating a project:

After creation, pom.xml has the following dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

Of course, Thymeleaf can be used in other places as well as in Spring Boot, but Spring Boot provides a full set of automated configuration solutions for Thymeleaf. This set of configuration class attribute in the org. Springframework. Boot. Autoconfigure. Thymeleaf. ThymeleafProperties, part of the source code is as follows:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
        private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
        public static final String DEFAULT_PREFIX = "classpath:/templates/";
        public static final String DEFAULT_SUFFIX = ".html";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = DEFAULT_PREFIX;
        private String suffix = DEFAULT_SUFFIX;
        private String mode = "HTML";
        private Charset encoding = DEFAULT_ENCODING;
        private boolean cache = true;
        / /...
}
Copy the code
  1. First of all by@ConfigurationPropertiesAnnotations,application.propertiesThe prefix forspring.thymeleafIs bound to properties in this class.
  2. The first threestaticVariables define the default encoding format, the view parser prefix, suffix, and so on.
  3. As you can see from the first three lines of configuration,ThymeleafThe default location of the template isresources/templatesDirectory, the default suffix ishtml
  4. These configurations, if not provided by the developer, are used by default, if provided by the developer, inapplication.propertiesIn order tospring.thymeleafThe configuration starts.

And the automatic configuration classes that Spring Boot provides for Thymeleaf that we just mentioned, Is the org. Springframework. Boot. Autoconfigure. Thymeleaf. ThymeleafAutoConfiguration, part of the source code is as follows:

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {}Copy the code

As you can see, in this automated configuration class, we import ThymeleafProperties, and then the @conditionalonClass annotation indicates that when TemplateMode and SpringTemplateEngine classes are currently in the system, The current automated configuration class will only take effect, that is, as soon as thymeleaf-related dependencies are introduced into the project.

These default configurations can be used with very little change. If the developer has special requirements, you can configure a property starting with Spring.thymeleaf in application.properties.

  • Create a Controller

Now we can create the Controller, and we can actually do nothing with the Thymeleaf dependency. Create the following IndexController:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId((long) i);
            u.setName("javaboy:" + i);
            u.setAddress("Shenzhen." + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "index"; }}public class User {
    private Long id;
    private String name;
    private String address;
    / / omit getter/setter
}
Copy the code

Return the logical view name + data in IndexController. The logical view name is index, which means we need to provide a Thymeleaf template file named index.html in the Resources/Templates directory.

  • Create Thymeleaf

      
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>Serial number</td>
        <td>The user name</td>
        <td>address</td>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.address}"></td>
    </tr>
</table>
</body>
</html>
Copy the code

In Thymeleaf, a set is traversed by the TH :each instruction, and the display of data is realized by the TH :text instruction.

Note that the index.html introduces the Thymeleaf namespace at the top.

After the configuration is complete, you can start the project, access the /index interface, and see the data in the collection:

In addition, Thymeleaf supports fetching variables from Model directly in JS. For example, there is a variable username in IndexController:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("username"."Bill");
        return "index"; }}Copy the code

In the page template, you can get this variable directly from JS:

<script th:inline="javascript">
    var username = [[${username}]];
    console.log(username)
</script>
Copy the code

This is one of the features of Thymeleaf.

Manual rendering

We can also render the Thymeleaf template manually, which is useful for sending emails. For example, I created a new email template in the Resources /templates directory, as follows:


      
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>Hello, welcome to<span th:text="${username}"></span>To join XXX Group, your entry information is as follows:</p>
<table border="1">
    <tr>
        <td>position</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>salary</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
<img src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/6/12/16b494107e529c34~tplv-t2oaga2asx-image.image" alt="">
</body>
</html>
Copy the code

In this HTML template, there are several variables, we want to render the HTML template as a String String, and then send the String by email, so how do we render manually?

@Autowired
TemplateEngine templateEngine;
@Test
public void test1(a) throws MessagingException {
    Context context = new Context();
    context.setVariable("username"."javaboy");
    context.setVariable("position"."Java Engineer");
    context.setVariable("salary".99999);
    String mail = templateEngine.process("mail", context);
    // omit message sending
}
Copy the code
  1. To render, we first need to inject a TemplateEngine object, which is configured in Thymeleaf’s automated configuration class (that is, we have this instance when we introduce Thymeleaf’s dependencies).
  2. We then construct a Context object to hold variables in.
  3. The render is called to the process method, which returns the rendered HTML string, which we then send out.

These are a few key points of Spring Boot’s integration with Thymeleaf. For more information on the use of the Thymeleaf page template itself, you can refer to the Thymeleaf documentation at www.thymeleaf.org.

conclusion

In this article, we briefly introduce some problems in integrating Spring Boot and Thymeleaf. You can read the official Thymeleaf documentation to learn more about Thymeleaf usage. This article I have uploaded to GitHub, welcome everyone star :github.com/lenve/javab…

If you have any questions about this article, please leave a comment. Pay attention to the public account [Jiangnan little Rain], focus on Spring Boot+ micro service and front and back end separation and other full stack technology, regular video tutorial sharing, after attention to reply to Java, get Songko for you carefully prepared Java dry goods!