⏹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;
@Component("htmlHandleUtil")
public class HtmlUtil {
public static String formatNumber(Number num) {
return NumberUtils.format(num, 1, NumberPointType.COMMA, java.util.Locale.JAPAN);
}
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}">
<div>[[*{@htmlHandleUtil.formatNumber(id)}]]</div>
<hr>
<div>[[*{address}]]</div>
<hr>
<div th:utext="*{@htmlHandleUtil.replaceLinebreak(address)}"></div>
</div>
</body>
</html>
🥳4.效果
