企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一、内置对象 > 官方文档:[Thymeleaf 3.0 基础对象](https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects) ### 七大基础对象: * `${#ctx}`上下文对象,可用于获取其它内置对象。 * `${#param}`: 上下文变量。 * `${#locale}`:上下文区域设置。 * `${#request}`: HttpServletRequest对象。 * `${#response}`: HttpServletResponse对象。 * `${#session}`: HttpSession对象。 * `${#servletContext}`: ServletContext对象。 ### 用法示例 **locale对象操作:** ~~~ <div th:text="${#locale.getLanguage() + '_' + #locale.getCountry()}"></div> ~~~ **session对象操作:** ~~~ <div th:text="${session.foo}?:('zoo')"></div> <div th:text="${session.size()}"></div> <div th:text="${session.isEmpty()}"></div> <div th:text="${session.containsKey('foo')}"></div> ~~~ ![](https://img.kancloud.cn/5d/ad/5dad02a18482f94f9d3c78555f3aae68_920x247.png) 运行程序观察 ![](https://img.kancloud.cn/ae/d5/aed5b3801b82b600d6b73d145291daf7_400x194.png) 可以看到取到了语言zh、国家CN、foo对象没有值取的默认值zoo、session因为是空的所以size等于0、isEmpy为true、是否包含foo对象为true。 这时去添加session对象 ![](https://img.kancloud.cn/43/cf/43cf2526a86e7903437e98ed372e1973_385x122.png) ![](https://img.kancloud.cn/a4/a9/a4a92cbb07cf0de949ec95ab8f226410_894x572.png) 在执行会发现 ![](https://img.kancloud.cn/d3/62/d3623eb6bb1872631ec9b64b0db2587c_381x199.png) ## 二、 常用的工具类: > 官方文档:[Thymeleaf 3.0 工具类](https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects) * `#strings`:字符串工具类 * `#lists`:List 工具类 * `#arrays`:数组工具类 * `#sets`:Set 工具类 * `#maps`:常用Map方法。 * `#objects`:一般对象类,通常用来判断非空 * `#bools`:常用的布尔方法。 * `#execInfo`:获取页面模板的处理信息。 * `#messages`:在变量表达式中获取外部消息的方法,与使用#{...}语法获取的方法相同。 * `#uris`:转义部分URL / URI的方法。 * `#conversions`:用于执行已配置的转换服务的方法。 * `#dates`:时间操作和时间格式化等。 * `#calendars`:用于更复杂时间的格式化。 * `#numbers`:格式化数字对象的方法。 * `#aggregates`:在数组或集合上创建聚合的方法。 * `#ids`:处理可能重复的id属性的方法。 ### 用法举例: **date工具类之日期格式化** 使用默认的日期格式(toString方法) 并不是我们预期的格式:`Mon Dec 03 23:16:50 CST 2018` 此时可以通过时间工具类`#dates`来对日期进行格式化:`2018-12-03 23:16:50` ~~~ <input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/> ~~~ ![](https://img.kancloud.cn/14/63/1463d5ee5589f33f4eaf7a75f2a8ba40_833x114.png) ![](https://img.kancloud.cn/0f/85/0f85537e2a4ad8d84a1a06fd494d6d3b_848x102.png) ![](https://img.kancloud.cn/e7/db/e7db909bcd1c779da0848aa19b729102_736x111.png) **首字母大写** ~~~ /* * Convert the first character of every word to upper-case */ ${#strings.capitalizeWords(str)} // also array*, list* and set* ~~~ ![](https://img.kancloud.cn/e0/40/e040824ec3af6eab90043def363c3923_834x159.png) ![](https://img.kancloud.cn/97/5b/975b8d54138f44b38c8ca559e3c11515_738x114.png) **list方法** ~~~ /* * Compute size */ ${#lists.size(list)} /* * Check whether list is empty */ ${#lists.isEmpty(list)} ~~~