(3) SpringBoot -- template engine thymeleaf

1, Template engine supported by SpringBoot

1. Tymeleaf (official recommendation)

2,FreeMarker

3,Groovy

4,mustache

 

Why isn't JSP recommended for SpringBoot?

1. JSP is more intrusive to the page.

2. The management of web container version.

 

2, About thymeleaf

Perfect separation of front and back ends

 

3, Realize MVC

The documents stored in different packages are as follows:

1. Introduce dependency

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

2. Write controller

/*
 * Copyright (c) 2018 solidwang. All Rights Reserved
 */
package com.solid4j.controller;

import com.solid4j.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: solidwang
 * @date: 2018/4/19 Forenoon 10:35 am
 */
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {

    @RequestMapping("")
    public ModelAndView index(){
        List<User> userList = new ArrayList<User>();
        User user1 = new User("solidwang", "solidwang@126.com");
        User user2 = new User("jobs", "jobs@me.com");
        userList.add(user1);
        userList.add(user2);

        ModelAndView modelAndView = new ModelAndView("/index");
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }
}

3. Template file (index.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>learn Resources</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<div>
    <h1>Thymeleaf test</h1>
    <table border="1" cellspacing="1" cellpadding="0">
        <tr>
            <td>Full name</td>
            <td>passport</td>
        </tr>
        <tr th:each="user : ${userList}">
            <td th:text="${user.username}">solidwang</td>
            <td th:text="${user.passport}">solidwang@me.com</td>
        </tr>
    </table>
</div>
</body>
</html>

4. The test results are as follows:

5. Precautions

If you want to refresh the template page in real time, you need to configure the application.properties file, spring.thymeleaf.cache=false. If it still does not take effect, you can compile the html file once.

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
 #Turn off the cache during development, or you will not be able to see the real-time page
spring.thymeleaf.cache=false
#thymeleaf end

Tags: Thymeleaf Spring SpringBoot JSP

Posted on Fri, 03 Apr 2020 00:21:19 -0700 by Saphod