SpringBoot-Thymeleaf模板引擎-07

1. 模板引擎

  1. 前端给我们的页面,如果是html页面,我们需要转成jsp页面,jsp好处就是,当我们查出一些数据转发到JSP页面后,我们可以用jsp实现数据的显示以及交互
  2. jsp支持Java的代码,但SpringBoot是以jar包的方式打包的,用的是嵌入式的Tomcat,所以默认不支持jsp
  3. 但SpringBoot推荐可以使用模板引擎:
  • 作用:写一个页面模板,eg有一些值是动态的,我们写一些表达式,而这些值是从后台封装的一些数据,然后把这个模板和这个数据交给模板引擎,他就会按照这个数据帮助解析,然后填充到指定的位置.

引入Thymelf

找到对应的pom依:

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

Maven会自动下载jar包

2. Thymeleaf

按照SpirngBoot的自动配置原理看一下Thymeleaf的自动配置规则,需要找Thymeleaf的自动配置类:ThymeleafProperties


@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
}

能看出其中默认的前缀和后缀,现在需要把html页面放在类路径下的templates下,thymeleaf就可以自动帮助渲染.好处是不用任何配置,只需要将其放在指定的文件夹下即可!

3. 测试

  1. 编写一个TestController

@Controller
public class TestController {

    @RequestMapping("/t1")
    public String test1(){
        //classpath:/templates/test.html
        return "test";
    }
}
  1. 编写一个测试页面 test.html放在templates目录下
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>sli</title>
</head>
<body>
<h1>测试页面</h1>
</body>
</html>

3.启动项目,测试

4. Thymeleaf语法学习

  1. 修改测试请求,增加数据传输(修改controller类)
@RequestMapping("/t1")
public String test1(Model model){
    //存入数据
    model.addAttribute("msg","Hello,Thymeleaf");
    //classpath:/templates/test.html
    return "test";
}
  1. 需要在html中加入命名空间约束
    xmlns:th="http://www.thymeleaf.org"
  2. 修改前端页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>sli</title>
</head>
<body>
<h1>测试页面</h1>

<!--th:text就是将div中的内容设置为它指定的值,和之前学习的Vue一样-->
<div th:text="${msg}"></div>
</body>
</html>
  1. 启动测试
    测试页面输出Hello,Thymeleaf

5. 练习

  1. 编写一个controller,存一些数据
@RequestMapping("/t2")
public String test2(Map<String,Object> map){
    //存入数据
    map.put("msg","<h1>Hello</h1>");
    map.put("users", Arrays.asList("sli","1f"));
    //classpath:/templates/test.html
    return "test";
}
  1. 测试页面取出数据

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>js</title>
</head>
<body>
<h1>测试页面</h1>

<div th:text="${msg}"></div>
<!--不转义-->
<div th:utext="${msg}"></div>

<!--遍历数据-->
<!--th:each每次遍历都会生成当前这个标签:官网#9-->
<h4 th:each="user :${users}" th:text="${user}"></h4>

<h4>
    <!--行内写法-->
    <span th:each="user:${users}">[[${user}]]</span>
</h4>

</body>
</html>
  1. 启动项目测试,访问8080端口能输出遍历之后的合集
posted @ 2021-09-25 07:58  1_f  阅读(25)  评论(0)    收藏  举报