JAVA后台数据使用thymeleaf渲染html页面

一、前言

本篇介绍如何使用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>
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大头程序员不头大

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值