第十二章:SpringBoot_Web开发——(引入thymeleaf模板)

总目录:SpringBoot学习教程


1.以前我们使用的界面都是jsp的格式,对数据进行一些遍历,判断等等,支持非常强大的功能。

2.SpringBoot项目是以jar包的方式,而不是web。我们用的还是默认的嵌入式tomcat,不支持jap。

3.如果我们使用纯静态的页面,我们开发就非常的麻烦了。

所以,SpringBoot推荐我们使用模板引擎。一些常见的模板引擎的有。(JSP,Velocity,Freemarker,Thymeleaf)

不管使用哪个模板引擎,他们的思想都是一样的。

我们写一个页面模板,比如有些值是动态的,我们写一些表达式,而这些值从哪里来的,我们来组装一些数据,然后我们把这个模板和这些数据交个模板引擎,模板引擎按照这个数据,帮忙把这些表达式解析,填充到指定的位置,然后这些数据最终生成一个我们想要的内容,给我们显示出来。这就是模板引擎。

不同模板引擎直接的语法有点区别。

(一)第一步,在pom中引入依赖。

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

如果我们光添加了上面的依赖,这个模板引擎也可以用,但是不是最新的版本。

切换版本:如果我们想要使用最新的版本,就需要在pom文件中的 properties标签中添加配置。

<properties>
                <!--布局功能的支持程序thymeleaf3主程序layout2以上版本-->
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
	</properties>

(二)第二步,Thymeleaf使用&语法

1.必须在classpath:/templates/ 下面的页面才能使用templates模板引擎,templates就能自动渲染

定义一个类Controller类:

@Controller
public class HelloController {
    @RequestMapping("/hello111")
    public String HelloTest(){
        //他就会去 classpath:/templates下面寻找 hello.html
        return "hello";
    }
}

定义一个hello.html页面:


访问:



语法:参考这个教程 https://blog.csdn.net/u014042066/article/details/75614906


我写的demo:

controller:

@Controller
public class HelloController {
    @RequestMapping("/hello111")
    public String HelloTest(){
        //他就会去 classpath:/templates下面寻找 hello.html
        return "hello";
    }

    @RequestMapping("/success")
    public String Test(Map<String,Object> map){
        map.put("hello","<h1>你好</h1>");
        map.put("user", Arrays.asList("科比","湖人"));
        return "success";
    }

}

success.html页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>成功</h1>

<hr/>

<div th:text="${hello}">  </div>
<!--不转义,就应该显示一个大标题-->
<div  th:utext="${hello}">  </div>
<hr/>
<!--使用th:each 标签  遍历user  变量名是u
th:each 写在哪个标签里面,每次遍历的时候这个标签都会生成一个
下面这个就会生成2个h4标签    科比 湖人
-->

<h4 th:text="${u}" th:each="u:${user}"></h4>
<hr/>
<h4>
    <span th:each="u:${user}">[[${u}]]</span>
</h4>

</body>
</html>

访问http://localhost:8080/success

显示:



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值