当前位置:网站首页>Thymeleaf uses background custom tool classes to process text

Thymeleaf uses background custom tool classes to process text

2022-07-05 14:58:00 fengyehongWorld

1. Custom tool class

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;

/*  Take a custom tool class and put it in Spring Alias in container ;  If you don't take it , Default to lowercase class name htmlUtil */ 
@Component("htmlHandleUtil")
public class HtmlUtil {
    

	/** *  Add a comma separator to the number  * * @param num  The number  * @return  Add the number after the comma  */
	public static String formatNumber(Number num) {
    
		return NumberUtils.format(num, 1, NumberPointType.COMMA, java.util.Locale.JAPAN);
	}

	/** *  Convert line breaks to  <br /> label  * * @param content  Before conversion  * @return  After the transformation  */
	public static String replaceLinebreak(String content) {
    
		return StringUtils.replace(StringUtils.escapeXml(content), System.getProperty("line.separator"), "<br />");
	}
}

2. The data returned from the background to the front

ZTestEntity zTestEntity = new ZTestEntity();
//  The number has no thousand separator 
zTestEntity.setId("100000");
//  The text contains line breaks 
zTestEntity.setAddress(" The universe  \r\n  Banking department  \r\n  The earth  \r\n  China ");

@GetMapping("/init")
public ModelAndView init() {
    
    
    ZTestEntity entity = service.init();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    //  The data from the background is transferred to the foreground 
    modelAndView.addObject("entity", entity);
    return  modelAndView;
}

3. The foreground uses the tool class customized by the background to process

<!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}">
    	<!--  among htmlHandleUtil For background tools bean name  -->
        <div>[[*{@htmlHandleUtil.formatNumber(id)}]]</div>
        <hr>
        <!-- No tool class is used to deal with text with line breaks -->
        <div>[[*{address}]]</div>
        <hr>
        <!--  Use th:utext Ensure that the html Line break <br> Tags are not parsed as plain text  -->
        <div th:utext="*{@htmlHandleUtil.replaceLinebreak(address)}"></div>
    </div>
</body>
</html>

🥳4. effect

 Insert picture description here

原网站

版权声明
本文为[fengyehongWorld]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051410196602.html