Spring Boot2 series of tutorials (nine) Spring Boot integration Thymeleaf

While it is slowly developing around the popular end of the separation, but according to Song Ge learned, there are still some companies in the development of the front and rear ends, regardless of make, regardless of the backend developed in the previous pages we'll need to back-end template (in fact, even before and after the end of the separation will need to use page templates in some scenarios, such as sending e-mail template).

Early Spring Boot also supports the use of Velocity as a page template, now the Spring Boot has not supported Velocity, and page templates major support Thymeleaf and Freemarker, of course, Java as the most basic page template Jsp, Spring Boot is supported, just use too much trouble.

Song Ge intends to use the three articles to tell you about each of these three page template technology.

Today we take a look at the major consolidation in the Spring Boot Thymeleaf in!

Thymeleaf Profile

Thymeleaf is a new generation of Java template engine, which is similar to Velocity, FreeMarker and other traditional Java template engine, but with the traditional difference is that Java template engine, Thymeleaf support HTML prototype.

It allows engineers to open the front view styles directly in the browser, but also allows engineers to combine real back-end data viewing display, at the same time, SpringBoot provides Thymeleaf automated provisioning solution, it is very easy to use Thymeleaf in SpringBoot in.

In fact, Thymeleaf addition to showing basic HTML, for page rendering outside, can also be rendered as an HTML fragment, for example, when we do send a message, you can send e-mail as a template Thymeleaf.

In addition, because Thymeleaf template suffix .html, you can directly open the browser, therefore, very convenient preview.

Integrate

  • Create a project

Spring Boot in integrating Thymeleaf very easy, when you can just add Thymeleaf create a project:

Once created, pom.xml dependent on the following:

<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>

Of course, not only can be used in Thymeleaf Spring Boot can also be used in other places, but Spring Boot for Thymeleaf provides a set of automated configuration program, this set of configuration attributes in the class org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties, some of the source code 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;
        //...
}
  1. First through @ConfigurationPropertiesannotations, the application.propertiesprefix for the spring.thymeleafconfiguration and properties of this class of binding.
  2. The first three staticvariables define the default encoding format, ViewResolver prefix, suffix and the like.
  3. Front three rows configuration, can be seen, Thymeleafthe default location of the template in resources/templatesthe directory, the default suffix html.
  4. These configurations, if developers do not provide their own, then use the default, if they provided, then application.propertiesto the spring.thymeleafstart of the relevant configuration.

And we have just mentioned, automated configuration class Spring Boot to Thymeleaf provided, it is org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, part of the source code as follows:

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

It can be seen in this class automated configuration, first import ThymeleafPropertiesand @ConditionalOnClassannotation indicates that when the current system exists TemplateModeand SpringTemplateEngineclass, the current class of automated configuration to take effect, that is, as long as the project was introduced in Thymeleafthe relevant dependencies, this configuration will take effect .

The default configuration we almost do not need to make any changes can be directly used. If developers have special needs, you can configure the properties to begin with in order to spring.thymeleaf application.properties in.

  • Creating Controller

Then we can create Controller, in fact, after the introduction of Thymeleaf dependence, we can not do any configuration. The new IndexController as follows:

@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("深圳:" + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "index";
    }
}
public class User {
    private Long id;
    private String name;
    private String address;
    //省略 getter/setter
}

In IndexControllerreturn logical view name + data logic in the view called index, which means we need to resources/templatesprovide a directory named index.htmlthe Thymeleaftemplate file.

  • Creating Thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>地址</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>

In Thymeleafby th:eachinstructions through a collection, display data through th:textimplemented instructions,

Note that index.htmlthe top be introduced thymeleafnamespace.

Once configured, you can start the project, and access / index interfaces, you can see in the data set:

In addition, Thymeleafsupport jsis available directly in Modelthe variables. For example, IndexControllerthere is a variable username:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("username", "李四");
        return "index";
    }
}

In the page template, you can get directly in the js to this variable:

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

This function is regarded as one of the characteristics Thymeleaf it.

Manual rendering

But we said is to return a Thymeleaf template, we can also manually render Thymeleaf template, this time in general is useful to send a message, for example, I created a mail template in resources / templates directory, as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>hello 欢迎 <span th:text="${username}"></span>加入 XXX 集团,您的入职信息如下:</p>
<table border="1">
    <tr>
        <td>职位</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>薪水</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
<img src="http://www.javaboy.org/images/sb/javaboy.jpg" alt="">
</body>
</html>

This is a HTML template, there are several variables, we want to render this HTML template into a String string, then the string sent through the mail, then how to manually render it?

@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
    Context context = new Context();
    context.setVariable("username", "javaboy");
    context.setVariable("position", "Java工程师");
    context.setVariable("salary", 99999);
    String mail = templateEngine.process("mail", context);
    //省略邮件发送
}
  1. When rendering, we need to inject a TemplateEngine object that is configured in Thymeleaf automated configuration class (that is, when we introduce depend Thymeleaf of this example there).
  2. Then a Context object used to store configuration variables.
  3. Call the process method for rendering, the return value is the rendered HTML string of the method, then we will send out the string.

These are a few key points of the Spring Boot integration Thymeleaf, regarding itself more usage Thymeleaf this page template, you can refer to the documentation Thymeleaf: https://www.thymeleaf.org .

to sum up

This article shows you a brief introduction a few problems when Spring Boot and Thymeleaf integration, it is quite simple, you can read more about the use Thymeleaf official documentation of learning Thymeleaf. This paper cases I've uploaded to GitHub: https://github.com/lenve/javaboy-code-samples

About this, there are discussion questions please leave a message.

Public concern number [south] a little rain, focused on Spring Boot + Micro service and front and rear ends of separation full stack technology, video tutorials on a regular basis to share concerns reply after Java, Java dry Song Ge receive carefully prepared for you!

Guess you like

Origin www.cnblogs.com/lenve/p/11606097.html