(3) SpringBoot -- template engine thymeleaf

1, Template engine supported by SpringBoot

1. Tymeleaf (official recommendation)





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


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
public class ThymeleafController {

    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");

        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">
    <title>learn Resources</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

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

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
 #Turn off the cache during development, or you will not be able to see the real-time page
#thymeleaf end

Tags: Thymeleaf Spring SpringBoot JSP

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