一、前言

本篇介绍如何使用thymeleaf从后台获取数据后渲染至html页面上。

二、使用方法
1、注入依赖

<!-- Thymeleaf 模板引擎 -->
<dependency>
   <groupId>org.thymeleaf</groupId>
   <artifactId>thymeleaf</artifactId>
   <version>3.0.9.RELEASE</version>
</dependency>

2、新建渲染工厂工具类


import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.util.Map;
 
/**
 * @author Ray
 */
public class HTMLTemplateUtils {
 
    private final static TemplateEngine engine=new TemplateEngine();
 
    /**
     * 使用 Thymeleaf 渲染 HTML
     * @param template  HTML模板
     * @param params 参数
     * @return  渲染后的HTML
     */
    public static String render(String template,Map<String,Object> params){
        Context context = new Context();
        context.setVariables(params);
        return engine.process(template,context);
    }

3、测试以上工具类

public class Test {
    public static void main(String[] args) {
        String template = "<p th:text='${title}'></p>";
        HashMap<String, Object> map = new HashMap<>();
        map.put("title","hello world");
        String render = HTMLTemplateUtils.render(template, map);
        System.out.println("渲染之后的字符串是:"+render);
    }
}

4、新建前端Html示例页面


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${name}">工程项目</h1>
<ul>
    <li th:each="item: ${array}" th:text="${item}">项目名称</li>
</ul>
</body>
</html>

5、将后台数据渲染至Html页面上


public class HTMLTest2 {
 
    public static void main(String[] args) throws IOException {
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        //模板所在目录,从resources目录开始的相对路径。
        resolver.setPrefix("");
        //模板文件后缀
        resolver.setSuffix(".html");
        TemplateEngine engine = new TemplateEngine();
        engine.setTemplateResolver(resolver);
 
        //构造上下文(Model)
        List<String> array = new ArrayList<>();
        array.add("AA");
        array.add("BB");
        array.add("CC");
        Context context = new Context();
        context.setVariable("name", "工程名称");
        context.setVariable("array", array);
 
        //渲染模板
        FileWriter writer = new FileWriter("src/main/resources/result.html");
        engine.process("example",context,writer);
        writer.flush();
        writer.close();
    }
}

6、在resources目录下生成result.html文件


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>工程名称</h1>
<ul>
    <li>AA</li>
    <li>BB</li>
    <li>CC</li>
</ul>
</body>
</html>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐