首页 > 编程语言 > 详细

0010Springboot整合thymeleaf

时间:2019-11-21 22:55:49      阅读:112      评论:0      收藏:0      [点我收藏+]

1、pom.xml中添加thymeleaf的起步依赖

2、编写html文件并放在classpath:/templates/路径下

3、编写controller并返回字符串,会到classpath:/templates/路径下找 字符串.html的文件解析并返回

pom.xml中添加thymeleaf的起步依赖

<!--引入thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
若想更改thymeleaf版本号,可在pom.xml中添加如下配置
<properties>
<java.version>1.8</java.version>
<!--更改thymeleaf版本-->
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 适配 layout2以上版本 -->
<!-- thymeleaf2 layout1-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>


编写html文件并放在classpath:/templates/路径下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功</h1>
转义为普通字符,输出字符串"<h1>您好!</h1>"
<div th:text="${hello}"> </div>
<!--不转义为普通字符,即输出为h1标题大小的字符串"您好!"-->
<div th:utext="${hello}"> </div>

<!-- th:each每次遍历都会生成当前标签,所以会生成3个h4标签-->
<h4 th:each="user:${users}" th:text="${user}"></h4>
<h4>
<!--/*[[]]相当于th:text*/-->
<span th:each="user:${users}" >[[${user}]]</span>
<!--/*[[]]相当于th:utext*/-->
<span th:each="user:${users}" >[(${user})]</span>
<!--/*加斜杠星形式的代码在解析时会被移除,上边带th:utext形式的代码,如果注释中不加斜杠星,
访问该页面解析时会报错,审查元素时看不到这部分注释,其他形式的注释在审查元素时可以看到*/-->
</h4>
</body>
</html>
编写controller并返回字符串,会到classpath:/templates/路径下找 字符串.html的文件解析并返回
package com.myself.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Map;

@Controller
public class HelloController {

@RequestMapping("/hello")
//注意此处不能写@ResponseBody,否则就不会解析success.html文件了,而是之间返回"success"字符串给页面
//同理,类上也不能写@RestController,因为它相当于@Controller和@ResponseBody的合体
//@ResponseBody
public String hello(Map<String,Object> map){
map.put("hello","<h1>您好!</h1>");
map.put("users", Arrays.asList("张三","李四","王五"));
return "success";
}
}

另外thymeleaf的语法可访问thymeleaf的官网进行学习,为方便查看也可导出pdf进行查看

技术分享图片

 

 

若有理解不到之处,望指正!

0010Springboot整合thymeleaf

原文:https://www.cnblogs.com/xiao1572662/p/11908564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!