在velocity中使用日期格式化或无效的原因

本文详细介绍了如何利用Apache Velocity模板引擎进行数据渲染的过程,包括配置依赖、创建模板、设置编码及模板路径,以及通过VelocityContext填充变量并最终生成HTML文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:导入依赖
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>
<dependency>
    <groupId>velocity-tools</groupId>
    <artifactId>velocity-tools</artifactId>
    <version>1.4</version>
</dependency>

第二步:模板velocity (  test.vm 中的主要内容)

<td>

第一个 $!date.format("yyyy年MM月dd日",$!createTime)
第二个 $!img.format("yyyy年MM月dd日",$!createTime)

</td>

第三步:代码

VelocityEngine ve = new VelocityEngine();
//设置编码格式
ve.setProperty(VelocityEngine.ENCODING_DEFAULT, "UTF-8");
ve.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8");
ve.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8");
//模板存放路径(此处放在D盘)
ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "D://");
// 初始化
ve.init();
// 导入 名为 test.vm 的模板文件(完整路径应为 D://test.vm)
Template template = ve.getTemplate("test.vm");

VelocityContext ctx = new VelocityContext();
//此处的  img、date 对应 第二步的红色部分 若不对应设置格式化将无效
ctx.put("img", new DateTool());
ctx.put("date", new DateTool());
//时间变量 createTime 对应第二步中的蓝色部分 $!createTime 填充变量
ctx.put("createTime", "2019-12-23 17:53:16");
StringWriter sw = new StringWriter();
//合成填充
template.merge(ctx, sw);

String r = sw.toString();
//打印在控制看效果
System.err.println(r);
//输出为html文件看效果
File file = new File("D://new.html");
FileWriter fileWriter = new FileWriter(file);
fileWriter.append(r);
fileWriter.flush();
fileWriter.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值