首先引入maven jar依賴html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>
接着在application.properties內配置 thymeleafweb
#設置thymeleaf 注意:必定要在web後面添加一個 斜槓 /,不然找不到文件
spring.thymeleaf.prefix=classpath:/web/
spring.thymeleaf.suffix=.html
#設置thymeleaf不按照HTML5嚴格的檢查標籤
spring.thymeleaf.mode=LEGACYHTML5
模板默認仍是放在templates文件夾下,這裏我修改到web文件夾下面了spring
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.example.demo.entity.Student; @Controller @RequestMapping("/student/") public class StudentController { @RequestMapping("show") public String show(Model model) { Student stu = new Student(); stu.setId(1001); stu.setName("小明"); model.addAttribute("student", stu); model.addAttribute("str", "this is spring boot freemarker"); return "show"; } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>thymeleaf</h1> <h3 th:text="${str}">h3</h3> id:<span th:text="${student.id}"></span><br> name:<span th:text="${student.name}"></span> </body> </html>