Springboot+Thymeleaf 整合(2020最新)

    科技2025-08-05  14

    本文章适合刚开始学习springboot的小伙伴;

    1,建一个springboot项目,目录结如下:

    配置pom.xml,添加thymeleaf依赖

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

    2,在properties文件中配置thymeleaf(主要配置访问路径,编码,和缓存)别忘了这里端口号用的是8082

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

    3,添加controller

    import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class thymeleafController { @RequestMapping(value = "/index") public String index(){ return "index"; } @RequestMapping("/test") public String test(ModelMap map){ map.addAttribute("name","thymeleaf"); return "test"; } }

    这里index是静态页面,test是动态页面

    4,添加index.html 

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> 真好,没有乱码 <h1> hello thymeleaf </h1> </body> </html>

    添加test.html

    <!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 th:text="${name}">Hello Thymeleaf~~~~~~~</h1> </body> </html>

    index页面返回结果

    test页面返回结果

     

    到此先结束了,继续往下学习。

    Processed: 0.010, SQL: 8