SpringBoot集成 Thymeleaf,附Thymeleaf语法讲解

SpringBoot中使用Thymeleaf

  1. pom依赖
        <!--thymeleaf视图模板框架-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--shiro模板视图权限标签扩展-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>${thymeleaf-shiro.version}</version>
        </dependency>
  1. 配置项
spring:
  ## thymeleaf模板设置
  thymeleaf:
    prefix: classpath:/templates
    suffix: .html
    mode: HTML
    encoding: utf-8
    servlet.content-type: text/html
    cache: false
  1. 创建LoginController控制器,loginPage函数用来显示登陆页
@Controller
public class LoginController {

    @GetMapping("/login")
    public String loginPage(Model model) {
        ProjectProperties properties = SpringApplicationContextUtil.getBean(ProjectProperties.class);
        model.addAttribute("isCaptcha", properties.isCaptchaOpen());
        return "/login";
    }
}
  1. 创建templates模板目录,并创建login.html登录页
    目录结构
    login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="/common/template :: header(~{::title},~{::link},~{::style})">
    <title>EasyBoot登录</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/login.css}">
</head>
<body class="layui-layout-login">
    <div class="login-bg">
        <div class="cover"></div>
    </div>
    <div class="login-content" th:th:classappend="${isCaptcha} ? 'captcha'">
        <h1 class="login-box-title"><i class="fa fa-fw fa-user"></i>登录</h1>
        <form class="layui-form" th:action="@{/login}" method="post">
            <div class="layui-form-item">
                <label class="layui-icon layui-icon-username" for="username"></label>
                <input class="layui-input" type="text" name="username" id="username" placeholder="用户名">
            </div>
            <div class="layui-form-item">
                <label class="layui-icon layui-icon-password" for="password"></label>
                <input class="layui-input" type="password" name="password" id="password" placeholder="密码">
            </div>
            <div th:if="${isCaptcha}" class="layui-form-item captcha-item">
                <label class="layui-icon layui-icon-vercode"></label>
                <input class="layui-input" type="text" name="captcha" autocomplete="off" placeholder="验证码">
                <img class="captcha-img" th:src="@{/captcha}" />
            </div>
            <div class="layui-form-item">
                <input type="checkbox" name="rememberMe" title="记住我" lay-skin="primary">
                <a class="layui-layout-right forget-password" href="javascript:alert('请联系超级管理员!')">忘记密码?</a>
            </div>
            <button type="submit" class="layui-btn layui-btn-fluid ajax-login"><i class="fa fa-sign-in fa-lg fa-fw"></i> 登录</button>
        </form>
        <div class="layui-layer-loading login-page-loading"><div class="layui-layer-content"></div></div>
    </div>
<script th:replace="/common/template :: script"></script>
<script th:src="@{/js/login.js}" charset="utf-8"></script>
</body>
</html>

当中用到了嵌入模板common/template.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="header(title, link, style)">
    <th:block th:if="${title == null}">
        <title>EasyBoot后台</title>
    </th:block>
    <th:block th:if="${title != null}">
        <title th:replace="${title}">title</title>
    </th:block>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="shortcut icon" th:href="@{/mo-favicon.ico}" type="image/x-icon">
    <link rel="stylesheet" th:href="@{/css/plugins/font-awesome-4.7.0/css/font-awesome.min.css}"  media="all">
    <link rel="stylesheet" th:href="@{/lib/layui-v2.3.0/css/layui.css}"  media="all">
    <link rel="stylesheet" th:href="@{/css/main.css}"  media="all">
    <th:block th:if="${link != null}">
        <th:block th:replace="${link}"></th:block>
    </th:block>

    <th:block th:if="${style != null}">
        <th:block th:replace="${style}"></th:block>
    </th:block>
</head>
<body>
    <th:block th:fragment="script">
        <script th:src="@{/lib/layui-v2.3.0/layui.js}" charset="utf-8"></script>
        <script th:src="@{/js/main.js}" charset="utf-8"></script>
    </th:block>
</body>
</html>

启动项目,显示如下
页面显示

Thymeleaf语法

  1. th属性
    常用th属性解读
    html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。
    ①th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
    ②th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6
    ③th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
    ④th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3
    ⑤th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1
    ⑥th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
    ⑦th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4
    ⑧th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5
    常用th属性使用
    使用Thymeleaf属性需要注意点以下五点:
    ①若要使用Thymeleaf语法,首先要声明名称空间: xmlns:th=“http://www.thymeleaf.org”
    ②设置文本内容 th:text,设置input的值 th:value,循环输出 th:each,条件判断 th:if,插入代码块 th:insert,定义代码块 th:fragment,声明变量 th:object
    ③th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div。
    ④变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。
    ⑤th:insert,th:replace,th:include 三种插入代码块的效果相似,但区别很大。
    参考login.html
  2. 标准表达式语法
  • ~{…}:代码块表达式
  • #{…}:消息表达式
  • @{…}:链接表达式
  • *{…}:选择变量表达式
  • ${…}:变量表达式
    变量表达式使用频率最高,其功能也是非常的丰富。所以我们先从简单的代码块表达式开始,然后是消息表达式,再是链接表达式,最后是变量表达式,随带介绍选择变量表达式

~{…} 代码块表达式
支持两种语法结构
推荐:~{templatename::fragmentname}
支持:~{templatename::#id}
templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment=“fragmentname”
id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器,支持标签选择。
代码块表达式的使用
代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,
th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,
th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中
参考login.html、template.html

<!-- template.html-->
<head th:fragment="header(title, link, style)">
...
</head>

<!-- login.html -->
<head th:replace="/common/template :: header(~{::title},~{::link},~{::style})">
...
</head>

#{…} 消息表达式
消息表达式一般用于国际化的场景。结构:th:text="#{msg}" 。
@{…} 链接表达式

  • 不管是静态资源的引用,form表单的请求,凡是链接都可以用@{…} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问
  • 链接表达式结构:
    无参:@{/xxx}
    有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
    引入本地资源:@{/项目本地的资源路径}
    引入外部资源:@{/webjars/资源在jar包中的路径}
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link th:href="@{/lib/layui-v2.3.0/css/layui.css}" rel="stylesheet">
<form class="form-login" th:action="@{/login}" th:method="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>

${…}变量表达式
变量表达式有丰富的内置方法,使其更强大,更方便。

  • 变量表达式功能
    ①可以获取对象的属性和方法
    ②可以使用ctx,vars,locale,request,response,session,servletContext内置对象
    ③可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点介绍)
  • 常用的内置对象
    ①ctx :上下文对象。
    ②vars :上下文变量。
    ③locale:上下文的语言环境。
    ④request:(仅在web上下文)的 HttpServletRequest 对象。
    ⑤response:(仅在web上下文)的 HttpServletResponse 对象。
    ⑥session:(仅在web上下文)的 HttpSession 对象。
    ⑦servletContext:(仅在web上下文)的 ServletContext 对象
    这里以常用的Session举例,用户刊登成功后,会把用户信息放在Session中,Thymeleaf通过内置对象将值从session中获取。
// java 代码将用户名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通过内置对象直接获取
th:text="${session.userinfo}"

常用的内置方法
①strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
②numbers:数值格式化方法,常用的方法有:formatDecimal等
③bools:布尔方法,常用的方法有:isTrue,isFalse等
④arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
⑤lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
⑥maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
⑦dates:日期方法,常用的方法有:format,year,month,hour,createNow等

总结

1 . Thymeleaf 是Spring Boot 官方推荐的Java模版引擎框架,其文件扩展名为.html
2. Thymeleaf 几乎支持所有的html属性,用于赋值的th:text和th:value,用于循环遍历的th:each,用于条件判断的th:if
3. Thymeleaf 提供四种标准的表达式,有丰富内置方法的${},用于国际化的#{},用于代码插入的~{},用于处理链接的@{}
4. 一定要注意循环遍历的th:each和代码插入的th:insert用法,尽量避免破坏html结构的细节问题

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值