freemarker 入门

本文介绍了一个使用Freemarker模板引擎实现的具体示例。通过一个包含商品列表展示及用户类型的判断逻辑的案例,展示了如何将Java后端数据传递到前端进行渲染。涉及Freemarker的基本用法、宏定义、条件判断、列表遍历等功能。

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

[b]Header.ftl文件代码[/b]
[code]<#macro title color="red">
<font color="${color}" size="16px"><#nested></font>
</#macro>
<#assign version = "1.0">
<html>
<head>
<title>Hello World ${version}</title>
</head>
<body>[/code]

[b]copyright.ftl文件代码[/b]
[code]<table>jamesby copyright</table>
</body>
</html>[/code]

[b]helloworld.ftl文件代码[/b]
[code]<#import "header.ftl" as header>
<@header.title color="red">Hello World ${header.version}</@header.title><br>
<#if user.usertype = "buyer">${message} ${user.userName} Buyer!<#else>${message} ${user.userName} Seller!</#if>
<#if satuday??>No Trade<#else>Please trade.........</#if>
<#-- Goods List -->
<table border=1>
<tr>
<td>Goods Name</td>
<td>Price</td>
<td>updateDate</td>
</tr>
<#list goods as being>
<tr>
<td>${being.name?html}</td>
<td align="right">
<#if being.price gt 500>
<font color=red>${being.price!"NULL"}</font>
<#else>
<font color=blue>${being.price}</font>
</#if>
</td>
<td>${being.dt?string("yyyy-MM-dd HH:mm:ss")}
</td>
</#list>
</table>
<table>
<#list ["buy"]+["sell"] as x>
<a href="#">${x}</a>
</#list>
</table
<#include "copyright.ftl">[/code]

[b]java文件代码[/b]
[code]package test.t0121;

import java.util.*;
import java.io.*;
import freemarker.template.*;

public class HelloWorld{
private Configuration cfg;

public Configuration getCfg() {
return cfg;
}
public void init() throws Exception{
cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("D:/freemarker_project/template"));
}
public static void main(String[] args) throws Exception
{
User user = new User("james",User.USER_BUYER);
HelloWorld obj = new HelloWorld();
obj.init();
Map root = new HashMap();
root.put("message", "Hello ");
root.put("user",user);

List goods = new ArrayList();
root.put("goods",goods);

Goods goodsA = new Goods("GoodsA",10,new Date());
Goods goodsB = new Goods("GoodsB",100,new Date());
Goods goodsC = new Goods("GoodsC",1000,new Date());
goods.add(goodsA);
goods.add(goodsB);
goods.add(goodsC);

Template t = obj.getCfg().getTemplate("helloworld.ftl");

Writer out = new OutputStreamWriter(new FileOutputStream("D:/freemarker_project/out/helloword.html"),"GBK");
t.process(root, out);
System.out.println("Successfull................");
}
}[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值