拓展
点击跳转哦~:SpringBoot系列学习汇总和拓展
@[toc]
一、介绍 Thymeleaf
- 前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。
- jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。
- 作用: 比如值是动态的,这些值的来源是后台封装返回的数据。模板引擎可以将数据、表达式解析和填充到我们指定的位置。
二、引入 Thymeleaf
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
复制代码
- ③查看是否下载成功
三、分析 Thymeleaf
- ①打开ThymeleafProperties类
-
②我们可以在其中看到默认的前缀和后缀!
- 我们只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了。
- 使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可!
-
③测试:
- 编写controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class helloWorldController {
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String hello(){
return "test";
}
}
复制代码
- 编写测试页面
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>我是标题一!!!!</h1>
</body>
</html>
复制代码
- 启动测试
复制代码
四、Thymeleaf 语法
- ①controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class helloWorldController {
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String hello(Model model){
//存入数据
model.addAttribute("msg","我是大大丁大大");
return "test";
}
}
复制代码
- ②html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>大大丁大大</title>
</head>
<body>
<h1>我是标题一!!!!</h1>
<!-- 测试thymeleaf填充数据-->
<div th:text="${msg}"></div>
</body>
</html>
复制代码
- ③启动后测试结果
五、Thymeleaf 总结
- ①在线文档:点击跳转
- ②如何阅读?可以使用翻译软件来看,因为博主英文也不大行,所以看着也痛苦!
- ③如何寻找所需的东西?需要啥找啥即可。全部背下来不现实,用的时候知道哪里有即可。
- ④我们可以使用任意的 th:attr 来替换Html中原生属性的值!
路漫漫其修远兮,吾必将上下求索~ 如果你认为i博主写的不错!写作不易,请点赞、关注、评论给博主一个鼓励吧~转载请注明出处哦~