SpringBoot 整合模板引擎
一、SpringBoot 整合 Thymeleaf
1、首先在 pom.xml 文件中引入 thymeleaf 依赖
<dependencies>
<!-- springBoot web的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springBoot 引入thymeleaf的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2、创建存放视图的目录
目录位置:src/main/resources/templates
templates :该目录是安全的;意味着该目录下的内容是不允许外界直接访问的。
特点:Thymelaef是通过他特定语法对html的标记做渲染
3、编写 Controller
/**
* Thymeleaf入门案例
*
*
*/
@Controller
public class DemoController {
@RequestMapping("/show")
public String showInfo(Model model){
model.addAttribute("msg", "Thymeleaf 第一个案例");
return "index";
}
}
一般项目中会看到这种页面的访问方式写法:
@RequestMapping("/{page}")
public String showPage(@PathVariable String page){
return page;
}
这里穿插一下 @PathVariable 注解:
@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值
@PathVariable是用来获得请求url中的动态参数的
@PathVariable("xxx")
通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“)
@RequestMapping("show5/{id}/{name}")
public ModelAndView test5(@PathVariable("id") Long ids ,@PathVariable("name") String names){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","占位符映射:id:"+ids+";name:"+names);
mv.setViewName("hello2");
return mv;
}
请求路径示例:http://localhost:8080/hello/show5/1/james
4、创建视图文件 index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Thymeleaf入门</title>
</head>
<body>
Thymeleaf模板引擎
<span th:text="Hello"></span>
<hr/>
<span th:text="${msg}"></span>
</body>
</html>
5、编写启动类
/**
*
*Thymeleaf入门案例
*
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
6、项目中经常会使用到配置文件 application.properties
在资源配置文件中加入thymeleaf相关配置;会有不同的写法:
#
# thymeleaf静态资源配置
#
##############################################
# 默认路径
spring.thymeleaf.prefix=classpath:/templates/
# 后缀
spring.thymeleaf.suffix=.html
# 模板格式
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
二、Thymeleaf语法
1、变量输出与字符串操作
1.1 th:text
<table border="1" style="width:300px; padding: 0;" cellpadding="0" cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="user : ${list}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>
th:text与th:utext<br/>
<span th:text="${user.desc}"></span><!--th:text 不会进行转译-->
<br/>
<span th:utext="${user.desc}"></span><!--th:utext 会进行转译-->
1.2、th:value
th:value 可以将一个值放入到input标签的value中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>更新操作</title>
</head>
<body>
<form th:action="@{/users/editUser}" method="post">
<input type="hidden" name="id" th:field="${user.id}">
用户姓名:<input type="text" name="name" th:field="${user.name}"><br>
用户年龄:<input type="text" name="age" th:value="${user.age}"><br>
<input type="submit" value="确定更改">
</form>
</body>
</html>
上面用到了 th:field="
u
s
e
r
.
n
a
m
e
"
和
t
h
:
v
a
l
u
e
=
"
{user.name}" 和 th:value="
u s e r . n a m e " 和 t h : v a l u e = " {user.age}" 结果没有区别,都是可以回显,修改后提交值也都可以更新。
<div th:object="${user}"><!--定义一个对象,指定为user,下面的user都可以省略不写-->
用户姓名:<input th:id="*{name}" th:name="*{name}" th:value="*{name}"/>
<br/>
用户年龄:<input th:value="*{age}"/>
<br/>
用户生日:<input th:value="*{#dates.format(birthday,'yyyy-MM-dd')}"/><!--时间格式转换-->
<br/>
</div>
1.3、判断字符串是否为空
Thymeleaf内置对象 ; 注意语法;
1.3.1、调用内置对象一定要用 #
1.3.2、大部分的内置对象都以s结尾 strings、numbers、dates
${#strings.isEmpty(key)} 判断字符串是否为空,如果为空返回true,否则返回false
${#strings.contains(msg,‘T’)} 判断字符串是否包含指定的子串,如果包含返回true,否则返回false
${#strings.startsWith(msg,‘a’)} 判断当前字符串是否以子串开头,如果是返回true,否则返回false
${#strings.endsWith(msg,‘a’)} 判断当前字符串是否以子串结尾,如果是返回true,否则返回false
${#strings.length(msg)} 返回字符串的长度
${#strings.indexOf(msg,‘h’)} 查找子串的位置,并返回该子串的下标,如果没找到则返回-1
${#strings.substring(msg,13)} ${#strings.substring(msg,13,15)} 截取子串,用户与jdk String类下SubString方法相同
${#strings.toUpperCase(msg)} ${#strings.toLowerCase(msg)} 字符串转大小写。
2、日期格式化处理
${#dates.format(key)} 格式化日期,默认的以浏览器默认语言为格式化标准
${#dates.format(key,‘yyy/MM/dd’)} 按照自定义的格式做日期转换
${#dates.year(key)} ; ${#dates.month(key)} ; ${#dates.day(key)} year:取年 ; Month:取月 ; Day:取日
3、条件判断
3.1、 th:if
<span th:if="${sex} == '男'">
性别:男
</span>
<span th:if="${sex} == '女'">
性别:女
</span>
3.2、 th:switch
<div th:switch="${id}">
<span th:case="1">ID为1</span>
<span th:case="2">ID为2</span>
<span th:case="3">ID为3</span>
</div>
4、迭代遍历
4.1、 th:each
<table border="1" style="width:300px;" cellpadding="0" cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>操作</th>
</tr>
<tr th:each="user : ${list}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
<td>
<a th:href="@{/users/findUserById(id=${user.id})}">更新</a>
<a th:href="@{/users/deleteUserById(id=${user.id})}">删除</a>
</td>
</tr>
</table>
4.2、 ht:each 状态变量
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Index</th>
<th>Count</th>
<th>Size</th>
<th>Even</th>
<th>Odd</th>
<th>First</th>
<th>lase</th>
</tr>
<tr th:each="u,var : ${list}">
<td th:text="${u.userid}"></td>
<td th:text="${u.username}"></td>
<td th:text="${u.userage}"></td>
<td th:text="${var.index}"></td>
<td th:text="${var.count}"></td>
<td th:text="${var.size}"></td>
<td th:text="${var.even}"></td>
<td th:text="${var.odd}"></td>
<td th:text="${var.first}"></td>
<td th:text="${var.last}"></td>
</tr>
</table>
状态变量属性
1,index:当前迭代器的索引 从0开始
2,count:当前迭代对象的计数 从1开始
3,size:被迭代对象的长度
4,even/odd:布尔值,当前循环是否是偶数/奇数 从0开始
5,first:布尔值,当前循环的是否是第一条,如果是返回true否则返回false
6,last:布尔值,当前循环的是否是最后一条,如果是则返回true否则返回false
4.3、 th:each迭代Map
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="maps : ${map}">
<td th:text="${maps}"></td>
</tr>
</table>
<th/>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="maps : ${map}">
<td th:each="entry:${maps}" th:text="${entry.value.userid}" ></td>
<td th:each="entry:${maps}" th:text="${entry.value.username}"></td>
<td th:each="entry:${maps}" th:text="${entry.value.userage}"></td>
</tr>
</table>
5、域对象操作
5.1、 HttpServletRequest
request.setAttribute(“req”, “HttpServletRequest”); Request:
5.2、HttpSession
request.getSession().setAttribute(“sess”, “HttpSession”); Session:
5.3、ServletContext
request.getSession().getServletContext().setAttribute(“app”, “Application”); Application:
6、URL表达式: th:href ; th:src
6.1、url表达式语法
基本语法:@{}
6.2、 绝对网址
绝对URL用于创建到其他服务器的链接。它们需要指定一个协议名称(http://或https ?/)开头。
<a th:href="@{http://www.baidu.com}">绝对路径</a><br/>
<a th:href="@{https://www.e-learn.cn/thymeleaf/}">
<a href="https://www.e-learn.cn/thymeleaf/">
6.3、 上下文相关URL (相对路径)
最常用的URL类型是上下文相关的。 这些URL是一旦安装在服务器上,就会与Web应用程序根相关联URL。 例如,如果将一个名称为myapp.war的文件部署到一个Tomcat服务器中,那么应用程序一般是通过URL:http://localhost:8080/myapp来访问,myapp就是上下文名称。
与上下文相关的URL以/字符开头:
如果应用程序访问URL为:http://localhost:8080/myapp,则此URL将输出:
<a href="/myapp/order/list">
<a th:href="@{/show}">相对路径</a>
6.4、与服务器相关URL
服务器相关的URL与上下文相关的URL非常相似,只是它们不假定URL要链接到应用程序上下文中的资源,因此允许链接到同一服务器中的不同上下文:
<a th:href="@{~/billing-app/showDetails.html}">
当前应用程序的上下文将被忽略,因此尽管应用程序部署在http:// localhost:8080 / myapp,但该URL将输出:
<a href="/billing-app/showDetails.html">
6.5、添加参数
如何向使用@{…}表达式创建的URL添加参数? 这也很简单:
<a th:href="@{/order/details(id=3)}">
上面示例代码,最终将输出为:
<a href="/order/details?id=3">
也可以添加几个参数,用逗号分隔它们:
<a th:href="@{/order/details(id=3,action='show_all')}">
上面代码将输出结果为:
<!-- 注意&符号在标签属性中进行HTML转义... -->
<a href="/order/details?id=3&action=show_all">
还可以使用正常参数的路径变量的形式包含参数,但在URL的路径中指定一个占位符:
<a th:href="@{/order/{id}/details(id=3,action='show_all')}">
上面输出结果为:
<a href="/order/3/details?action=show_all">
6.6、网址片段标识符
片段标识符可以包含在URL中,包含参数和不包含参数。 它们将始终包含在网址的基础上,参考以下代码:
<a th:href="@{/home#all_info(action='show')}">
执行输出结果如下 -
<a href="/home?action=show#all_info">