SpringBoot and Thymeleaf template engine and Demo

Overview

At present, the development period used a completely separated front-end and back-end mode, that is, the back-end only provides a data interface, and the front-end obtains data through AJAX requests. This mode requires no template engine at all.

The separation of front and back end is not conducive to SEO, because SEO is essentially a server to initiate a request to another server to parse the content of the request. Generally, the search engine does not execute the requested js file. If an HTML page does not render data on the server side, but only renders data on the browser side, then the HTML page requested by the search engine does not render data. This is not conducive to the content being searched by search engines. Therefore, the server renders some or all of the data before sending the page to the browser to ensure that there is data on the page, which is conducive to SEO.

In addition, the front-end separation mode will be slightly worse in performance. In some scenarios, it is more convenient to use a template engine such as an email template.
Common template engines:

  • Thymeleaf
  • Freemaker
  • JSP

The working principle of the template engine:
Insert picture description here
give the template and data to the template engine, and it will help us render the data onto the template, form an output, and then send it to the browser.

Thymeleaf

Thymeleaf official website

Thymeleaf is a modern server-side Java template engine for web and standalone environments. Thymeleaf's goal is to introduce elegant natural templates into the development workflow. This natural template is HTML, which can be displayed correctly in the browser or as a static prototype, allowing for more powerful collaboration in the development team. Thymeleaf is ideal for modern HTML5 JVM web development.

Thymeleaf can run in both networked and non-networked environments. Artists can view static effects while browsing the page, and also allow programmers to view dynamic page effects with data on the server. Thymeleaf supports HTML prototypes, and then adds additional attributes to HTML tags to achieve template + data display. When the browser interprets html, it will ignore undefined tag attributes, so Thymeleaf's template can be run statically; when data is returned to the page, the Thymeleaf tag will dynamically replace the static content, so that the page is dynamically displayed. THymeleaf is an HTML page.

.

Step 1: Integrate Thymeleaf and add dependencies in the project's pom.xml

<properties>
 		<!--使用最新的版本-->
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>

Step 2: Configure Thymeleaf in the application.yml file

spring:
        thymeleaf:
                prefix: classpath:/templates/
                check-template-location: true
                cache: false
                suffix: .html
                encoding: UTF-8
                content-type: text/html
                mode: HTML5

  • prefix: specifies the directory where the template is located
  • check-tempate-location: Check if the template path exists
  • cache: Whether to cache, set to false in development mode to avoid restarting the server after changing the template, set to true online to improve performance.
  • encoding & content-type: Set encoding and content type
  • mode: thymeleaf version 3.0.11 supports six types of templates for processing HTML (HTML5, HTML4, XHTML), XML, TEXT, JAVASCRIPT, CSS, RAW

Step 3: Write thymeleaf template file

Create a thymeleaf template article.html in the SpringBootProject / src / main / resources / templates directory:
Note: You must add the namespace xmlns: th = "http://www.thymeleaf.org/, otherwise Thymeleaf's custom tags will not prompt!

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
    <meta content="text/html;charset=UTF-8"/>
</head>
<body>
<table border="1" bgcolor="#f0ffff">
    <thead>
    <tr>
        <th>序号</th>
        <th>标题</th>
        <th>摘要</th>
        <th>创建时间</th>
    </tr>
    </thead>
    <!-- 使用th:each遍历 -->
    <tbody th:each="article : ${list}">
    <tr>
        <!-- 使用th:text属性输出 -->
        <td th:text="${article.id}"></td>
        <td th:text="${article.title}"></td>
        <td th:text="${article.summary}"></td>
        <td th:text="${article.createTime}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>

The fourth step: write the controller


// 注解是@Controller,而不是@RestController,因为@RestController会自动将返回结果转为字符串
@Controller
@RequestMapping("/article")
public class ArticlePageController {

    private final Logger logger = LoggerFactory.getLogger(ArticlePageController.class);
    @GetMapping("/articleList")
    // 参数的名称就是前台要用的传参名称
    public String getArticle(Model model,@RequestParam(defaultValue = "奋斗的历史") String title){
        // title是由前台传到后台来的,如果没有值的时候,就用默认值

        ArticleBean articleBean = new ArticleBean();
        articleBean.setId(1);
        articleBean.setTitle(title);
        articleBean.setSummary(10);
        articleBean.setCreateTime(new Date());
        List<ArticleBean> list = new ArrayList<>();
        list.add(articleBean);
        // 这里的key一定是list,因为模板里用的就是list,这样模板引擎才能将其对应上
        model.addAttribute("list",list);
        // 返回值是classpath:/templates/下的模板路径,路径的最后是模板名称,不用加后缀。
        return "article";
    }
}

Step 5: Start the service, test

Start the service:

~/Desktop/SpringBootProject$ mvn spring-boot:run

Insert picture description here

Why is the thymeleaf page placed in the templates folder, and if the suffix is ​​.html?

The SpringBoot framework will put the built-in supported functional components under the spring-boot-autoconfigure-2.2.6.RELEASE.jar
package, while the Thymeleaf framework is built-in support. So you can find the corresponding automatic configuration code in this package, namely ThymeleafProperties.java class, as shown in the figure:

Insert picture description hereOf course, the above default values ​​can be modified through the application.yml or application.properties files.

thanks for reading!

Published 381 original articles · praised 85 · 80,000 views +

Guess you like

Origin blog.csdn.net/weixin_40763897/article/details/105216801