步骤 2 : 先运行,看到效果,再学习 步骤 3 : 模仿和排错 步骤 4 : TestController 步骤 5 : test.html 步骤 6 : thymeleaf 内置工具 步骤 7 : Execution Info 步骤 8 : Messages 步骤 9 : URIs/URLs 步骤 10 : Conversions 步骤 11 : Dates 步骤 12 : Calendars 步骤 13 : Numbers 步骤 14 : Strings 步骤 15 : Objects 步骤 16 : Booleans 步骤 17 : Arrays 步骤 18 : Lists 步骤 19 : Sets 步骤 20 : Maps 步骤 21 : Aggregates 步骤 22 : IDs
本知识点是建立在上一个知识点可运行项目的基础上进行的改进,所以最好把上个知识点理解和消化了.
老规矩,先下载右上角的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
运行 Application.java 然后访问测试地址: http://127.0.0.1:8080/thymeleaf/test 可以看到如图所示的日期信息被格式化后的结果。 日期格式化的方式,就是借助了 thymeleaf 内置工具实现的。
在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。 采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。 推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。 这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来 这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
增加了日期对象,并且放在 "now" 这个变量上扔给视图
package com.how2java.springboot.web;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.how2java.springboot.pojo.Product;
@Controller
public class TestController {
@RequestMapping("/test")
public String test(Model m) {
String htmlContent = "<p style='color:red'> 红色文字</p>";
Product currentProduct =new Product(5,"product e", 200);
boolean testBoolean = true;
Date now = new Date();
List<Product> ps = new ArrayList<>();
ps.add(new Product(1,"product a", 50));
ps.add(new Product(2,"product b", 100));
ps.add(new Product(3,"product c", 150));
ps.add(new Product(4,"product d", 200));
ps.add(currentProduct);
ps.add(new Product(6,"product f", 200));
ps.add(new Product(7,"product g", 200));
m.addAttribute("now", now);
m.addAttribute("ps", ps);
m.addAttribute("htmlContent", htmlContent);
m.addAttribute("currentProduct", currentProduct);
m.addAttribute("testBoolean", testBoolean);
return "test";
}
}
使用#dates这个内置工具进行格式化日期
<div class="showing date"> <h2>格式化日期</h2> 直接输出日期 ${now}: <p th:text="${now}"></p> 默认格式化 ${#dates.format(now)}: <p th:text="${#dates.format(now)}"></p> 自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}: <p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p> </div> <!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all" href="../../webapp/static/css/style.css" th:href="@{/static/css/style.css}"/>
<script type="text/javascript" src="../../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>
<style>
h2{
text-decoration: underline;
font-size:0.9em;
color:gray;
}
div.date p{
padding-left:20px;
color:gray;
}
</style>
</head>
<body>
<div class="showing date">
<h2>格式化日期</h2>
直接输出日期 ${now}:
<p th:text="${now}"></p>
默认格式化 ${#dates.format(now)}:
<p th:text="${#dates.format(now)}"></p>
自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
<p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
</div>
<div class="showing">
<h2>遍历</h2>
<table>
<thead>
<tr>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr th:each="p: ${ps}">
<td th:text="${p.id}"></td>
<td th:text="${p.name}"></td>
<td th:text="${p.price}"></td>
</tr>
</tbody>
</table>
</div>
<div class="showing">
<h2>带状态遍历</h2>
<table>
<thead>
<tr>
<th>index</th>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr th:class="${status.even}?'even':'odd'" th:each="p,status: ${ps}">
<td th:text="${status.index}"></td>
<td th:text="${p.id}"></td>
<td th:text="${p.name}"></td>
<td th:text="${p.price}"></td>
</tr>
</tbody>
</table>
</div>
<div class="showing">
<h2>遍历 select </h2>
<select size="3">
<option th:each="p:${ps}" th:value="${p.id}" th:selected="${p.id==currentProduct.id}" th:text="${p.name}" ></option>
</select>
</div>
<div class="showing">
<h2>遍历 radio </h2>
<input name="product" type="radio" th:each="p:${ps}" th:value="${p.id}" th:checked="${p.id==currentProduct.id}" th:text="${p.name}" />
</div>
<div class="showing">
<h2>条件判断</h2>
<p th:if="${testBoolean}" >如果testBoolean 是 true ,本句话就会显示</p>
<p th:if="${not testBoolean}" >取反 ,所以如果testBoolean 是 true ,本句话就不会显示</p>
<p th:unless="${testBoolean}" >unless 等同于上一句,所以如果testBoolean 是 true ,本句话就不会显示</p>
<p th:text="${testBoolean}?'当testBoolean为真的时候,显示本句话,这是用三相表达式做的':''" ></p>
</div>
<div class="showing">
<h2>显示 转义和非转义的 html 文本</h2>
<p th:text="${htmlContent}" ></p>
<p th:utext="${htmlContent}" ></p>
</div>
<div class="showing">
<h2>显示对象以及对象属性</h2>
<p th:text="${currentProduct}" ></p>
<p th:text="${currentProduct.name}" ></p>
<p th:text="${currentProduct.getName()}" ></p>
</div>
<div class="showing" th:object="${currentProduct}">
<h2>*{}方式显示属性</h2>
<p th:text="*{name}" ></p>
</div>
<div class="showing">
<h2>算数运算</h2>
<p th:text="${currentProduct.price+999}" ></p>
</div>
<div class="showing">
<div th:replace="include::footer1" ></div>
<div th:replace="include::footer2(2015,2018)" ></div>
</div>
</body>
</html>
像 #date 这样的 thymeleaf内置工具有很多种,一共有如下16种。
Execution Info Messages URIs/URLs Conversions Dates Calendars Numbers Strings Objects Booleans Arrays Lists Sets Maps Aggregates IDs 并不是每一种都用得到,所以这里把他们的用法手册列出来了,将来用到的时候再来查看就行了。 ${#execInfo.templateName}
${#execInfo.templateMode}
${#execInfo.processedTemplateName}
${#execInfo.processedTemplateMode}
${#execInfo.templateNames}
${#execInfo.templateModes}
${#execInfo.templateStack}
${#execInfo.templateName} ${#execInfo.templateMode} ${#execInfo.processedTemplateName} ${#execInfo.processedTemplateMode} ${#execInfo.templateNames} ${#execInfo.templateModes} ${#execInfo.templateStack} ${#messages.msg('msgKey')}
${#messages.msg('msgKey', param1)}
${#messages.msg('msgKey', param1, param2)}
${#messages.msg('msgKey', param1, param2, param3)}
${#messages.msgWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsg(messageKeyArray)}
${#messages.listMsg(messageKeyList)}
${#messages.setMsg(messageKeySet)}
${#messages.msgOrNull('msgKey')}
${#messages.msgOrNull('msgKey', param1)}
${#messages.msgOrNull('msgKey', param1, param2)}
${#messages.msgOrNull('msgKey', param1, param2, param3)}
${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsgOrNull(messageKeyArray)}
${#messages.listMsgOrNull(messageKeyList)}
${#messages.setMsgOrNull(messageKeySet)}
${#messages.msg('msgKey')} ${#messages.msg('msgKey', param1)} ${#messages.msg('msgKey', param1, param2)} ${#messages.msg('msgKey', param1, param2, param3)} ${#messages.msgWithParams('msgKey', new Object[] {param1, param2, param3, param4})} ${#messages.arrayMsg(messageKeyArray)} ${#messages.listMsg(messageKeyList)} ${#messages.setMsg(messageKeySet)} ${#messages.msgOrNull('msgKey')} ${#messages.msgOrNull('msgKey', param1)} ${#messages.msgOrNull('msgKey', param1, param2)} ${#messages.msgOrNull('msgKey', param1, param2, param3)} ${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2, param3, param4})} ${#messages.arrayMsgOrNull(messageKeyArray)} ${#messages.listMsgOrNull(messageKeyList)} ${#messages.setMsgOrNull(messageKeySet)} ${#uris.escapePath(uri)}
${#uris.escapePath(uri, encoding)}
${#uris.unescapePath(uri)}
${#uris.unescapePath(uri, encoding)}
${#uris.escapePathSegment(uri)}
${#uris.escapePathSegment(uri, encoding)}
${#uris.unescapePathSegment(uri)}
${#uris.unescapePathSegment(uri, encoding)}
${#uris.escapeFragmentId(uri)}
${#uris.escapeFragmentId(uri, encoding)}
${#uris.unescapeFragmentId(uri)}
${#uris.unescapeFragmentId(uri, encoding)}
${#uris.escapeQueryParam(uri)}
${#uris.escapeQueryParam(uri, encoding)}
${#uris.unescapeQueryParam(uri)}
${#uris.unescapeQueryParam(uri, encoding)}
${#uris.escapePath(uri)} ${#uris.escapePath(uri, encoding)} ${#uris.unescapePath(uri)} ${#uris.unescapePath(uri, encoding)} ${#uris.escapePathSegment(uri)} ${#uris.escapePathSegment(uri, encoding)} ${#uris.unescapePathSegment(uri)} ${#uris.unescapePathSegment(uri, encoding)} ${#uris.escapeFragmentId(uri)} ${#uris.escapeFragmentId(uri, encoding)} ${#uris.unescapeFragmentId(uri)} ${#uris.unescapeFragmentId(uri, encoding)} ${#uris.escapeQueryParam(uri)} ${#uris.escapeQueryParam(uri, encoding)} ${#uris.unescapeQueryParam(uri)} ${#uris.unescapeQueryParam(uri, encoding)} ${#conversions.convert(object, 'java.util.TimeZone')}
${#conversions.convert(object, targetClass)}
${#conversions.convert(object, 'java.util.TimeZone')} ${#conversions.convert(object, targetClass)} ${#dates.format(date)}
${#dates.arrayFormat(datesArray)}
${#dates.listFormat(datesList)}
${#dates.setFormat(datesSet)}
${#dates.formatISO(date)}
${#dates.arrayFormatISO(datesArray)}
${#dates.listFormatISO(datesList)}
${#dates.setFormatISO(datesSet)}
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
${#dates.day(date)}
${#dates.month(date)}
${#dates.monthName(date)}
${#dates.monthNameShort(date)}
${#dates.year(date)}
${#dates.dayOfWeek(date)}
${#dates.dayOfWeekName(date)}
${#dates.dayOfWeekNameShort(date)}
${#dates.hour(date)}
${#dates.minute(date)}
${#dates.second(date)}
${#dates.millisecond(date)}
${#dates.create(year,month,day)}
${#dates.create(year,month,day,hour,minute)}
${#dates.create(year,month,day,hour,minute,second)}
${#dates.create(year,month,day,hour,minute,second,millisecond)}
${#dates.createNow()}
${#dates.createNowForTimeZone()}
${#dates.createToday()}
${#dates.createTodayForTimeZone()}
${#calendars.format(cal)}
${#calendars.arrayFormat(calArray)}
${#calendars.listFormat(calList)}
${#calendars.setFormat(calSet)}
${#calendars.formatISO(cal)}
${#calendars.arrayFormatISO(calArray)}
${#calendars.listFormatISO(calList)}
${#calendars.setFormatISO(calSet)}
${#calendars.format(cal, 'dd/MMM/yyyy HH:mm')}
${#calendars.arrayFormat(calArray, 'dd/MMM/yyyy HH:mm')}
${#calendars.listFormat(calList, 'dd/MMM/yyyy HH:mm')}
${#calendars.setFormat(calSet, 'dd/MMM/yyyy HH:mm')}
${#calendars.day(date)}
${#calendars.month(date)}
${#calendars.monthName(date)}
${#calendars.monthNameShort(date)}
${#calendars.year(date)}
${#calendars.dayOfWeek(date)}
${#calendars.dayOfWeekName(date)}
${#calendars.dayOfWeekNameShort(date)}
${#calendars.hour(date)}
${#calendars.minute(date)}
${#calendars.second(date)}
${#calendars.millisecond(date)}
${#calendars.create(year,month,day)}
${#calendars.create(year,month,day,hour,minute)}
${#calendars.create(year,month,day,hour,minute,second)}
${#calendars.create(year,month,day,hour,minute,second,millisecond)}
${#calendars.createForTimeZone(year,month,day,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,millisecond,timeZone)}
${#calendars.createNow()}
${#calendars.createNowForTimeZone()}
${#calendars.createToday()}
${#calendars.createTodayForTimeZone()}
${#numbers.formatInteger(num,3)}
${#numbers.arrayFormatInteger(numArray,3)}
${#numbers.listFormatInteger(numList,3)}
${#numbers.setFormatInteger(numSet,3)}
${#numbers.formatInteger(num,3,'POINT')}
${#numbers.arrayFormatInteger(numArray,3,'POINT')}
${#numbers.listFormatInteger(numList,3,'POINT')}
${#numbers.setFormatInteger(numSet,3,'POINT')}
${#numbers.formatDecimal(num,3,2)}
${#numbers.arrayFormatDecimal(numArray,3,2)}
${#numbers.listFormatDecimal(numList,3,2)}
${#numbers.setFormatDecimal(numSet,3,2)}
${#numbers.formatDecimal(num,3,2,'COMMA')}
${#numbers.arrayFormatDecimal(numArray,3,2,'COMMA')}
${#numbers.listFormatDecimal(numList,3,2,'COMMA')}
${#numbers.setFormatDecimal(numSet,3,2,'COMMA')}
${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}
${#numbers.arrayFormatDecimal(numArray,3,'POINT',2,'COMMA')}
${#numbers.listFormatDecimal(numList,3,'POINT',2,'COMMA')}
${#numbers.setFormatDecimal(numSet,3,'POINT',2,'COMMA')}
${#numbers.formatCurrency(num)}
${#numbers.arrayFormatCurrency(numArray)}
${#numbers.listFormatCurrency(numList)}
${#numbers.setFormatCurrency(numSet)}
${#numbers.formatPercent(num)}
${#numbers.arrayFormatPercent(numArray)}
${#numbers.listFormatPercent(numList)}
${#numbers.setFormatPercent(numSet)}
${#numbers.formatPercent(num, 3, 2)}
${#numbers.arrayFormatPercent(numArray, 3, 2)}
${#numbers.listFormatPercent(numList, 3, 2)}
${#numbers.setFormatPercent(numSet, 3, 2)}
${#numbers.sequence(from,to)}
${#numbers.sequence(from,to,step)}
${#strings.toString(obj)}
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}
${#strings.defaultString(text,default)}
${#strings.arrayDefaultString(textArr,default)}
${#strings.listDefaultString(textList,default)}
${#strings.setDefaultString(textSet,default)}
${#strings.contains(name,'ez')}
${#strings.containsIgnoreCase(name,'ez')}
${#strings.startsWith(name,'Don')}
${#strings.endsWith(name,endingFragment)}
${#strings.indexOf(name,frag)}
${#strings.substring(name,3,5)}
${#strings.substringAfter(name,prefix)}
${#strings.substringBefore(name,suffix)}
${#strings.replace(name,'las','ler')}
${#strings.prepend(str,prefix)}
${#strings.append(str,suffix)}
${#strings.toUpperCase(name)}
${#strings.toLowerCase(name)}
${#strings.arrayJoin(namesArray,',')}
${#strings.listJoin(namesList,',')}
${#strings.setJoin(namesSet,',')}
${#strings.arraySplit(namesStr,',')}
${#strings.listSplit(namesStr,',')}
${#strings.setSplit(namesStr,',')}
${#strings.trim(str)}
${#strings.length(str)}
${#strings.abbreviate(str,10)}
${#strings.capitalize(str)}
${#strings.unCapitalize(str)}
${#strings.capitalizeWords(str)}
${#strings.capitalizeWords(str,delimiters)}
${#strings.escapeXml(str)}
${#strings.escapeJava(str)}
${#strings.escapeJavaScript(str)}
${#strings.unescapeJava(str)}
${#strings.unescapeJavaScript(str)}
${#strings.equals(first, second)}
${#strings.equalsIgnoreCase(first, second)}
${#strings.concat(values...)}
${#strings.concatReplaceNulls(nullValue, values...)}
${#strings.randomAlphanumeric(count)}
${#objects.nullSafe(obj,default)}
${#objects.arrayNullSafe(objArray,default)}
${#objects.listNullSafe(objList,default)}
${#objects.setNullSafe(objSet,default)}
${#objects.nullSafe(obj,default)} ${#objects.arrayNullSafe(objArray,default)} ${#objects.listNullSafe(objList,default)} ${#objects.setNullSafe(objSet,default)} ${#bools.isTrue(obj)}
${#bools.arrayIsTrue(objArray)}
${#bools.listIsTrue(objList)}
${#bools.setIsTrue(objSet)}
${#bools.isFalse(cond)}
${#bools.arrayIsFalse(condArray)}
${#bools.listIsFalse(condList)}
${#bools.setIsFalse(condSet)}
${#bools.arrayAnd(condArray)}
${#bools.listAnd(condList)}
${#bools.setAnd(condSet)}
${#bools.arrayOr(condArray)}
${#bools.listOr(condList)}
${#bools.setOr(condSet)}
${#bools.isTrue(obj)} ${#bools.arrayIsTrue(objArray)} ${#bools.listIsTrue(objList)} ${#bools.setIsTrue(objSet)} ${#bools.isFalse(cond)} ${#bools.arrayIsFalse(condArray)} ${#bools.listIsFalse(condList)} ${#bools.setIsFalse(condSet)} ${#bools.arrayAnd(condArray)} ${#bools.listAnd(condList)} ${#bools.setAnd(condSet)} ${#bools.arrayOr(condArray)} ${#bools.listOr(condList)} ${#bools.setOr(condSet)} ${#arrays.toArray(object)}
${#arrays.toStringArray(object)}
${#arrays.toIntegerArray(object)}
${#arrays.toLongArray(object)}
${#arrays.toDoubleArray(object)}
${#arrays.toFloatArray(object)}
${#arrays.toBooleanArray(object)}
${#arrays.length(array)}
${#arrays.isEmpty(array)}
${#arrays.contains(array, element)}
${#arrays.containsAll(array, elements)}
${#arrays.toArray(object)} ${#arrays.toStringArray(object)} ${#arrays.toIntegerArray(object)} ${#arrays.toLongArray(object)} ${#arrays.toDoubleArray(object)} ${#arrays.toFloatArray(object)} ${#arrays.toBooleanArray(object)} ${#arrays.length(array)} ${#arrays.isEmpty(array)} ${#arrays.contains(array, element)} ${#arrays.containsAll(array, elements)} ${#lists.toList(object)}
${#lists.size(list)}
${#lists.isEmpty(list)}
${#lists.contains(list, element)}
${#lists.containsAll(list, elements)}
${#lists.sort(list)}
${#lists.sort(list, comparator)}
${#sets.toSet(object)}
${#lists.toList(object)} ${#lists.size(list)} ${#lists.isEmpty(list)} ${#lists.contains(list, element)} ${#lists.containsAll(list, elements)} ${#lists.sort(list)} ${#lists.sort(list, comparator)} ${#sets.toSet(object)} ${#sets.size(set)}
${#sets.isEmpty(set)}
${#sets.contains(set, element)}
${#sets.containsAll(set, elements)}
${#sets.size(set)} ${#sets.isEmpty(set)} ${#sets.contains(set, element)} ${#sets.containsAll(set, elements)} ${#maps.size(map)}
${#maps.isEmpty(map)}
${#maps.containsKey(map, key)}
${#maps.containsAllKeys(map, keys)}
${#maps.containsValue(map, value)}
${#maps.containsAllValues(map, value)}
${#maps.size(map)} ${#maps.isEmpty(map)} ${#maps.containsKey(map, key)} ${#maps.containsAllKeys(map, keys)} ${#maps.containsValue(map, value)} ${#maps.containsAllValues(map, value)} ${#aggregates.sum(array)}
${#aggregates.sum(collection)}
${#aggregates.avg(array)}
${#aggregates.avg(collection)}
${#aggregates.sum(array)} ${#aggregates.sum(collection)} ${#aggregates.avg(array)} ${#aggregates.avg(collection)} ${#ids.seq('someId')}
${#ids.next('someId')}
${#ids.prev('someId')}
${#ids.seq('someId')} ${#ids.next('someId')} ${#ids.prev('someId')}
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
问答区域
2019-06-13
内置工具类说明
8 个答案
松松仔 跳转到问题位置 答案时间:2021-06-29 感谢大佬!
很倒霉的死小孩 跳转到问题位置 答案时间:2021-02-02 好人一生平安
15779872975gy 跳转到问题位置 答案时间:2020-10-09 从上面浏览下来,就一直在想“要是有解释注释就太棒了”,真棒吖
jasonhww 跳转到问题位置 答案时间:2020-05-20 感谢
sparksun007 跳转到问题位置 答案时间:2019-12-10 已保留,感谢分享~
Heron 跳转到问题位置 答案时间:2019-11-19 感谢
bindi 跳转到问题位置 答案时间:2019-08-16 谢谢大佬
李敏 跳转到问题位置 答案时间:2019-07-18 感谢
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2019-02-09
站长,我怎样知道每一种的意思?
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|