ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

springboot简单使用(4)

2022-09-03 17:00:08  阅读:173  来源: 互联网

标签:springboot 简单 request 1.9 使用 new public 模板 name


1.9 第九章 Thymeleaf 模版

1.9.1 认识 Thymeleaf

Thymeleaf 是一个流行的模板引擎,该模板引擎采用 Java 语言开发

模板引擎是一个技术名词,是跨领域跨平台的概念,在 Java 语言体系下有模板引擎,在 C#、PHP 语言体系下也有模板引擎,甚至在 JavaScript 中也会用到模板引擎技术,Java 生态下 的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。

Thymeleaf 对网络环境不存在严格的要求,既能用于 Web 环境下,也能用于非 Web 环境 下。在非 Web 环境下,他能直接显示模板上的静态数据;在 Web 环境下,它能像 Jsp 一样从 后台接收数据并替换掉模板上的静态数据。它是基于 HTML 的,以 HTML 标签为载体, Thymeleaf 要寄托在 HTML 标签下实现。

Spring Boot 集成了 Thymeleaf 模板技术,并且 Spring Boot 官方也推荐使用 Thymeleaf 来 替代 JSP 技术,Thymeleaf 是另外的一种模板技术,它本身并不属于 Spring Boot,Spring Boot 只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的 Java Web 开发中,我们 往往会选择使用 Jsp 去完成页面的动态渲染,但是 jsp 需要翻译编译运行,效率低 Thymeleaf 的官方网站:http://www.thymeleaf.org

Thymeleaf 官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

 

例子:

1.9.2.2 pom.xml 主要依赖 pom.xml 主要依赖

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

1.9.2.3 application.properties 设置

#开发阶段设置为 false ,上线后设置为 true
spring.thymeleaf.cache=false

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
#设置模板的类型
spring.thymeleaf.mode=HTML

1.9.2.4 创建模版文件:在 resources/templates/目录下创建 demo.html

<body>
<table>
<tr><td>测试数据</td></tr>
<tr><td th:text="${name}"></td></tr>
</table>
</body>
</html>

1.9.2.5 创建 ThymeleafController

@Controller
public class ThymeleafController {

@RequestMapping("/thymeleaf")
public String thymeleafcontroller(HttpServletRequest request){
request.setAttribute("name","李斯");
return "demo";
}
}

1.9.2.6 运行 Application 类,在浏览器访问

 

1.9.3 表达式

表达式是在页面获取数据的一种 thymeleaf 语法。类似 ${key}

1.9.3.1 标准变量表达式 注意:th:text="" 是 Thymeleaf 的一个属性,用于文本的显示 语法: ${key}

说明:标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和 EL 中的 ${} 相 同。Thymeleaf 中的变量表达式使用 ${变量名} 的方式获取 Controller 中 model 其中的数据。 也就是 request 作用域中的数据。

创建 Student 类

Controller 增加方法

创建模版文件

模版文件(html)修改后,可以使用 idea—Build 菜单-Recompile 编译文件。重新 Recompile 即可生效。

 

1.9.3.2 1 选择变量表达式 语法:*{key} 说明:需要配和 th:object 一起使用。

选择变量表达式,也叫星号变量表达式,使用 th:object 属 性来绑定对象,选择表达式首先使用 th:object 来绑定后台传来的对象,然后使用 * 来代表这 个对象,后面 {} 中的值是此对象中的属性。

选择变量表达式 *{...} 是另一种类似于标准变量表达式 ${...} 表示变量的方法 选择变量表达式在执行时是在选择的对象上求解,而${...}是在上下文的变量 model 上求解

 

创建模板文件:

<p>学习选择表达式</p>
<div th:object="${mystudent}">
<p th:text="*{id}">id</p>
<p th:text="*{name}">name</p>

</div>
<p th:text="*{mystudent.name}"></p>

1.9.3.3 链接表达式(URL 表达式) 语法:@{链接 url} 说明:主要用于链接、地址的展示,可用于

<script src="...">、<link href="...">、<a href="...">、<form action="...">、<img src="">等,可以
在 URL 路径中动态获取数据

Controller 增加方法

@RequestMapping("/link")
public String linkcontroller(HttpServletRequest request){
request.setAttribute("stuid",111);

return "link";
}

@GetMapping("/query/student")
@ResponseBody
public String query(Integer id){
return "查询学生 id="+id;
}
@GetMapping("/find/school")
@ResponseBody
public String query2(Integer id, String name) {
return "查询 2,id=" + id + ",姓名=" + name;
}

)创建模版文件

<body>
<p>链接表达式</p>
<p>链接到绝对地址</p>
<a th:href="@{http://www.baidu.com}">百度</a>
<br/>
<br/>
<p>链接到相对地址</p>
<a th:href="@{/student}">相对地址没有传参数</a>
<br/>
<br/>
<p>链接到相对地址,传参数方式 1</p>
<a th:href="@{'/query/student?id='+${stuid}}">相对地址传参数方式
1</a>
<br/>i
<br/>
<p>链接到相对地址,传参数方式 2,推荐方式</p>
<a th:href="@{/find/school(id=${stuid},name='lisi')}">相对地址传参数
方式 2</a>
</body>

1.9.4 Thymeleaf 属性 大部分属性和 html 的一样,只不过前面加了一个 th 前缀。 加了 th 前缀的属性,是经过 模版引擎处理的。

1.9.4.1 th:action 定义后台控制器的路径,类似

标签的 action 属性,主要结合 URL 表达式,获取动态变量 ......

 

 

 

 

 

 

1.9.4.7.1 循环 List:

Controller 增加方法

@GetMapping("/eachlist")
public String eachlist(HttpServletRequest request){
List<student> list=new ArrayList<>();
list.add(new student(2,"张三"));
list.add(new student(3,"三"));
list.add(new student(4,"张"));
list.add(new student(5,"张三d1"));
request.setAttribute("studentlist",list);
return "eachlist";

}

创建模版文件

<p>在一个div中循环p</p>
<div th:each="stu:${studentlist}">
<p th:text="${stu.id}"></p>
<p th:text="${stu.name}"></p>
</div>

语法说明: th:each="user, iterStat : ${userlist}"中的 ${userList} 是后台传过来的集合

◼ user 定义变量,去接收遍历${userList}集合中的一个数据

◼ iterStat ${userList} 循环体的信息

◼ 其中 user 及 iterStat 自己可以随便取名

◼ interStat 是循环体的信息,通过该变量可以获取如下信息

index: 当前迭代对象的 index(从 0 开始计算)

count: 当前迭代对象的个数(从 1 开始计算)这两个用的较多

size: 被迭代对象的大小 current: 当前迭代变量

even/odd: 布尔值,当前循环是否是偶数/奇数(从 0 开始计算)

first: 布尔值,当前循环是否是第一个

last: 布尔值,当前循环是否是最后一个

注意:循环体信息 interStat 也可以不定义,则默认采用迭代变量加上 Stat 后缀,即 userStat

 

1.9.4.7.2 遍历数组 Array

Controller 增加方法

@GetMapping("/eacharray")
public String eacharray(HttpServletRequest request){
student stu[]=new student[3];
stu[0]=new student(1001,"关羽");
stu[1]=new student(1002,"赵云");
stu[2]=new student(1003,"张飞");
request.setAttribute("stuarray",stu);
return "eacharray";

}

创建模版文件

<p>在一个div中循环p</p>
<div th:each="stu:${stuarray}">
<p th:text="${stu.id}"></p>
<p th:text="${stu.name}"></p>
</div>

1.9.4.7.3 遍历 map

Controller 增加方法

@GetMapping("/eachmap")
public String eachmap(HttpServletRequest request){
Map<String,student> map=new HashMap<>();
map.put("stu1",new student(1001,"关羽"));
map.put("stu2",new student(1002,"张飞"));
map.put("stu3",new student(1003,"刘备"));

request.setAttribute("stumap",map);
return "eachmap";

}

创建模版文件

<p>在一个div中循环p</p>
<div th:each="stu,stuInter:${stumap}">
<p th:text="${stuInter.size}"></p>
<p th:text="${stuInter.count}"></p>
<p th:text="${stu.key}"></p>
<p th:text="${stu.value.id}"></p>
<p th:text="${stu.value.name}"></p>
</div>

1.9.4.8 条件判断 if

语法:th:if=”boolean 条件” , 条件为 true 显示体内容

th:unless 是 th:if 的一个相反操作

Controller 增加方法

@GetMapping("/if")
public String ifunless(HttpServletRequest request){

request.setAttribute("sex","m");
request.setAttribute("islog",true);
request.setAttribute("age",20);
request.setAttribute("name","");


return "if";

}

创建模版文件

<p th:if="${sex=='m'}">
性别为男
</p>
<p th:if="${sex=='f'}">
性别为女
</p>
<p th:if="${islog}">
已登录
</p>
<p th:if="${age<50}">
年龄小于50
</p>
<p th:if="5>0">
5>0
</p>

<p th:if="${name}">
name 是 ’‘
</p>

 

1.9.4.9 switch,case 判断语句

<div th:switch="${sex}">
<p th:case="f">显示男</p>
<p th:case="f">显示女</p>
<p th:case="*">未知</p>
</div>

一旦某个 case 判断值为 true,剩余的 case 则都当做 false,“*”表示默认的 case,前面的 case 都不匹配时候,执行默认的 case

 

 

1.9.4.10 th:inline:th:inline 有三个取值类型 (text, javascript 和 none)

1.9.4.10.1 内联 text:可以让 Thymeleaf 表达式不依赖于 html 标签,直接使用内敛表达式[[表达式]]即可获取动 态数据,要求在父级标签上加 th:inline = “text”属性

Controller 增加方法

@GetMapping("/inline")
public String inline(HttpServletRequest request){
request.setAttribute("sex","m");
request.setAttribute("islog",true);
request.setAttribute("age",20);
request.setAttribute("name","张飞");
request.setAttribute("myuser",new student(234,"李武"));
return "inline";

}

创建模版文件

<p>在一个div中循环p</p>
<div th:inline="text">
姓名为:[[${name}]]</br>
年龄为:[[${age}]]
</div>

<div>
性别:[[${sex}]]
登录:[[${islog}]]
</div>

1.9.4.10.2 内联 javascript

可以在 js 中,获取模版中的数据。 在上面的模版页面中,增加

<button onclick="fun()">单击按钮</button>
<script type="text/javascript" th:inline="javascript">
var name = [[${myuser.name}]];
var id = [[${myuser.id}]];
function fun() {
alert("click 用户是"+name+",他的 id 是"+id);
}
</script>

 

1.9.5 字面量

Controller 增加方法

@GetMapping("/thy/text")

public String text(Model model){

model.addAttribute("sex","m");

model.addAttribute("isLogin",true);

model.addAttribute("age",20);

model.addAttribute("name",null);

model.addAttribute("city","北京");

model.addAttribute("myuser",new SysUser(1005,"周向","f",23));

return "10-text"; }

1.9.5.1.1 文本字面量

用单引号'...'包围的字符串为文本字面量

<p th:text="'城市是'+${city}+' 用户登录'+${isLogin}"></p>

1.9.5.1.3 boolean 字面量

<p th:if="${isLogin == true}">用户登录了</p>

1.9.5.1.2 数字字面量

<p th:if="${age > 10}"> age > 10 </p>
<p th:if="20 > 5">20 大于 5</p>

1.9.5.1.4 null 字面量

<p th:if="${name == null}"> name 是 null </p>

1.9.6 字符串连接

<p>字符串的连接,1 使用'';2 使用|字符串内容|</p>
<p th:text="'城市是'+${city}+' 用户登录'+${isLogin}"></p>
<p th:text="|城市是${city}用户登录${isLogin}|"></p>

1.9.7 运算符

算术运算:+ , - , * , / , %

关系比较: > , < , >= , <= ( gt , lt , ge , le )

相等判断:== , != ( eq , ne )

<p th:if="${age > 10}"> age > 10 </p>
<p th:if="20 > 5">20 大于 5</p>
<p th:text="${sex =='m' ? '男':'女'}"></p>
<p th:text="${sex =='m' ? (isLogin?'男已经登录':'男的没有登录'):'女
'}"></p>

 

1.9.8 Thymeleaf 基本对象:模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由# 号开始引用,我们比较常用的内置对象

1.9.8.1 #request 表示 HttpServletRequest

1.9.8.2 #session 表示 HttpSession 对象

编写controller

@GetMapping("/baseobject")
public String baseobject(HttpServletRequest request, HttpSession session){
request.setAttribute("reqdata","request中的数据");
session.setAttribute("sesdata","session中的数据");
request.getSession().setAttribute("reqsesdata","request获得session的数据");

session.setAttribute("loginname","张三");
return "baseobject";
}

编写模板文件

<p th:text="${#request.getAttribute('reqdata')}">request作用域</p>
<p th:text="${#request.getServerName()}"></p>
<p th:text="${#request.getServerPort()}"></p>
<p th:text="${#request.getServletPath()}"></p></br>

<p th:text="${#session.getAttribute('sesdata')}">session 中数据</p>
<p th:text="${#session.getAttribute('loginname')}"></p>
<p th:text="${session.loginname}"></p>

#session表示HttpSession对象,session表示map对象,是#session的简单表示方式,用来获取session中指定的key的值

1.9.9 Tymeleaf 内置工具类对象

1.9.9.1 内置工具类对象

模板引擎提供的一组功能性内置对象,可以在模板中直接使用这些对象提供的功能方法 工作中常使用的数据类型,如集合,时间,数值,可以使用 Thymeleaf 的提供的功能性对 象来处理它们 内置功能对象前都需要加#号,内置对象一般都以 s 结尾

官方手册:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

#dates: java.util.Date 对象的实用方法,<span th:text="${#dates.format(curDate, 'yyyy-MM-dd
HH:mm:ss')}"></span>
#calendars: 和 dates 类似, 但是 java.util.Calendar 对象;
#numbers: 格式化数字对象的实用方法;
#strings: 字符串对象的实用方法: contains, startsWith, prepending/appending 等;
#objects: 对 objects 操作的实用方法;
#bools: 对布尔值求值的实用方法;
#arrays: 数组的实用方法;
#lists: list 的实用方法,比如<span th:text="${#lists.size(datas)}"></span>
#sets: set 的实用方法;
#maps: map 的实用方法;
#aggregates: 对数组或集合创建聚合的实用方法

1.9.9.2 例子

准备对象

public class Cat { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }

public class Dog { private String name; public String getName() { return name; } public void setName(String name) { this.name = name;}}

public class Zoo { private Dog dog; private Cat cat; public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } }

Controller 增加方法

@GetMapping("/thy/utilObject")
public String utilObject(Model model, HttpSession session){
model.addAttribute("mydate",new Date());
model.addAttribute("mynum",26.695);
model.addAttribute("mystr","bjpowernode");
List<String> mylist = Arrays.asList("a","b","c");
model.addAttribute("mylist",mylist);
//model.addAttribute("mylist",null);
session.setAttribute("loginname","zhangsan");
Dog dog = new Dog();
dog.setName("二哈");
Cat cat = new Cat();
cat.setName("英短");
Zoo zoo = new Zoo();
zoo.setCat(cat);
//zoo.setDog(dog);
zoo.setDog(null);
//
model.addAttribute("zoo",zoo);
return "12-utilObject";
}

创建模版文件

<p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"></p>
<p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss')}"></p>
<p th:text="${#dates.year(mydate)}"></p>
<p th:text="${#dates.month(mydate)}"></p>
<p th:text="${#dates.createNow()}" />
<br/>
<br/>
<p th:text="${#numbers.formatCurrency(mynum)}"></p>
<p th:text="${#numbers.formatDecimal(mynum,5,2)}"></p>
<br/>
<br/>
<p>处理@#strings</p>
<p th:text="${#strings.toUpperCase(mystr)}"></p>
<p th:text="${#strings.indexOf(mystr,'power')}"></p>
<p th:text="${#strings.substring(mystr,2,5)}"></p>
<p th:text="${#strings.concat(mystr,'----java 开发')}"></p>
<br/>
<br/>
<p>处理#lists</p>
<p th:text="${#lists.isEmpty(mylist)}"></p>
<p th:if="!${#lists.isEmpty(mylist)}" ></p>
<p th:text="${#lists.size(mylist)}"></p>
<p>空值</p>
<p th:text="${zoo?.dog?.name}"></p>

 

1.9.10 内容复用
自定义模板是复用的行为。可以把一些内容,多次重复使用。
1.9.10.1 定义模板
语法:th:fragment="top" , 定义摸模板,自定义名称是 top
例如:
<div th:fragment="top">
<p>动力节点</p>
<p>www.bjpowernode</p>
</div>
1.9.10.2 引用模板
语法:引用模板 ~{ templatename :: selector} 或者 templatename :: selector
例如:
<div th:insert="~{head :: top}"></div>
<div th:include="head :: top"></div>
1.9.10.3 模板例子
templates 目录下创建 head.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<!--定义模板, 就是一段页面代码-->
<div th:fragment="top">
<p>动力节点</p>
<p></p>
</div>
</body>
</html>

创建 footer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
footer

@copy; 动力节点 2020
</div>
</body>
</html>

在其他文件中,使用模板内容
<p>使用模板</p>
<div th:insert="~{head :: top}">
我是 div,insert 模板 top
</div>
<hr/>
<p>insert 模板 2</p>
<p th:insert="head :: top">
insert
</p>
<hr/>
<br/>
<p>包含</p>
<div th:include="head :: top">
我是当前的 div
</div>
<hr/>
<div th:include="footer :: html"></div>
<hr/>
<div th:include="footer" />

标签:springboot,简单,request,1.9,使用,new,public,模板,name
来源: https://www.cnblogs.com/zhangtaibing/p/16651255.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有