springboot+模版引擎(七)

1.springboot整合freemarker

略。对后端开发来说,成本比thymeleaf高。

2.springboot整合thymeleaf

好处:前后端不分离,但是成本低,上手起来简单,可以专注后端开发

如何整合?

1.引入依赖

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

2.配置application.property

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#关闭缓存,即使刷新。线上改为true
spring.thymeleaf.cache=false

3.在静态资源目录resource下新增thymeleaf文件夹,在该文件夹下新增index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello world~~~~~~~</h1>
</body>
</html>

  

4.在thymeleaf文件夹下新增center文件夹,在该文件夹下新增center.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1>center page</h1>
</body>
</html>

  

5.新增ThymeleafController类,访问模版

@Controller
@RequestMapping("th")
public class ThymeleafController {

	@RequestMapping("/index")
    public String index(ModelMap map) {
        map.addAttribute("name", "thymeleaf-anson2021b");
        return "thymeleaf/index";
    }
	
	@RequestMapping("center")
    public String center() {
        return "thymeleaf/center/center";
    }
}

  

6.启动服务,通过浏览器访问

127.0.0.1:8080/th/index或者直接访问html,127.0.0.1:8080/th/index.html

127.0.0.1:8080/th/center或者直接访问html,127.0.0.1:8080/th/center.html

获得html页内容,并且可见index模版获取name的内容为thymeleaf-anson2021b

posted @ 2021-11-08 11:07  XiaoLee-C  阅读(46)  评论(0编辑  收藏  举报