SpringBoot集成Thymeleaf

JSP的缺点

JSP会被编译成为Servlet,重量级。
JSP的缺点就是模板的优点。

除Thymeleaf,还有哪些模板

理论

SpringBoot模板默认配置的目录是templates

操作

  1. 引入Thymeleaf依赖(pom.xml)

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. 添加配置(可省略,则使用默认配置)

    spring.thymeleaf.suffix=.html
    spring.thymeleaf.mode=HTML5
    spring.thymeleaf.encoding=UTF-8
    spring.thymeleaf.servlet.content-type=text/html
    
  3. 代码开发和页面效果测试

    controller层:添加一个PageController

    package com.yeyouluo.hellospringboot.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * @Auther: yeyouluo
     * @Date: 2020/5/23
     */
    @Controller
    public class PageController {
    
        @RequestMapping("/index")
        public String index(Model model) {
            model.addAttribute("name", "yeyouluo");
            return "index";
        }
    }
    

    resources/templates目录下新建一个HTML5页面index.html,内容如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试页面</title>
    </head>
    <body>
        <h1>hello,Thymeleaf</h1>
        <p>by <span th:text="${name}"></span></p>
    </body>
    </html>
    
  4. 启动查看效果

其他收获

Thymeleaf参考资料