当前位置:网站首页>Thymeleaf 使用后台自定义工具类处理文本
Thymeleaf 使用后台自定义工具类处理文本
2022-07-05 14:10:00 【fengyehongWorld】
1.自定义工具类
package com.example.jmw.utils;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.NumberPointType;
import org.thymeleaf.util.NumberUtils;
import org.thymeleaf.util.StringUtils;
/* 给自定义工具类取一个放入Spring容器中的别名; 如果不取的话,默认为类名小写htmlUtil */
@Component("htmlHandleUtil")
public class HtmlUtil {
/** * 数字添加逗号分隔符 * * @param num 数值 * @return 添加逗号之后的数字 */
public static String formatNumber(Number num) {
return NumberUtils.format(num, 1, NumberPointType.COMMA, java.util.Locale.JAPAN);
}
/** * 将换行符转换为 <br />标签 * * @param content 转换前 * @return 转换后 */
public static String replaceLinebreak(String content) {
return StringUtils.replace(StringUtils.escapeXml(content), System.getProperty("line.separator"), "<br />");
}
}
2.后台向前台返回的数据
ZTestEntity zTestEntity = new ZTestEntity();
// 数字未添加千位分隔符
zTestEntity.setId("100000");
// 文本中含有换行符
zTestEntity.setAddress("宇宙 \r\n 银行系 \r\n 地球 \r\n 中国");
@GetMapping("/init")
public ModelAndView init() {
ZTestEntity entity = service.init();
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("test");
// 后台的数据传给前台
modelAndView.addObject("entity", entity);
return modelAndView;
}
3.前台使用后台自定义的工具类处理
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:object="${entity}">
<!-- 其中htmlHandleUtil为后台工具类的bean名称 -->
<div>[[*{@htmlHandleUtil.formatNumber(id)}]]</div>
<hr>
<!--未使用工具类处理携带换行符的文本-->
<div>[[*{address}]]</div>
<hr>
<!-- 使用th:utext确保后台的html换行<br>标签不被解析为纯文本 -->
<div th:utext="*{@htmlHandleUtil.replaceLinebreak(address)}"></div>
</div>
</body>
</html>
🥳4.效果

边栏推荐
猜你喜欢

Lepton 无损压缩原理及性能分析

Introduction, installation, introduction and detailed introduction to postman!

Tiflash compiler oriented automatic vectorization acceleration

Current situation, trend and view of neural network Internet of things in the future

网上电子元器件采购商城:打破采购环节信息不对称难题,赋能企业高效协同管理

金融壹賬通香港上市:市值63億港元 葉望春稱守正篤實,久久為功

TiCDC 6.0原理之Sorter演进

快消品行业SaaS多租户解决方案,构建全产业链数字化营销竞争力

Sqllab 1-6 exercise

神经网络物联网未来现状和趋势及看法
随机推荐
Linux下mysql数据库安装教程
01 、Solr7.3.1 在Win10平台下使用jetty的部署及配置
Enjoy what you want. Zhichuang future
VC开发非MFC程序内存泄漏跟踪代码
R Language ggplot2 Visualization: visualize linegraph, using Legend in Theme function. Paramètre de position emplacement de la légende personnalisée
TiCDC 6.0原理之Sorter演进
不相交集
R语言ggplot2可视化:gganimate包基于transition_time函数创建动态散点图动画(gif)、使用shadow_mark函数为动画添加静态散点图作为动画背景
LeetCode_ 67 (binary sum)
CYCA少儿形体礼仪 宁波市培训成果考核圆满落幕
日化用品行业智能供应链协同系统解决方案:数智化SCM供应链,为企业转型“加速度”
关于Apache Mesos的一些想法
Getting started with rce
Qingda KeYue rushes to the science and Innovation Board: the annual revenue is 200million, and it is proposed to raise 750million
3W principle [easy to understand]
Mysql database installation tutorial under Linux
非技术部门,如何参与 DevOps?
TiFlash 面向编译器的自动向量化加速
神经网络物联网未来现状和趋势及看法
分享 12 个最常用的正则表达式,能解决你大部分问题