JAVA中如何使用freemaker模版进行输出

首先你要有一个定义好的ftl文件,也就是最终输出的样式定义

<html>
<head>
<title></title>
</head>
<style type="text/css">

table {
	width: 800px;
	height: 400px;
	border: 2px solid black;
}

table thead tr td{
	text-align: center;
	border-right: 1px solid #C1DAD7;
	border-bottom: 1px solid #C1DAD7;
	background: #fff;
	font-size: 20px;
	font-weight: bold;
	color: #4f6b72;
}

.td1 {
	border-right: 1px solid #C1DAD7;
	border-bottom: 1px solid #C1DAD7;
	background: #fff;
	font-size: 14px;
	padding: 6px 6px 6px 12px;
	color: #4f6b72;
	width: 100px;
}

.td2 {
	border-right: 1px solid #C1DAD7;
	border-bottom: 1px solid #C1DAD7;
	background: #fff;
	font-size: 14px;
	padding: 6px 6px 6px 12px;
	color: #4f6b72;
	width: 500px;
}

</style>
<body>
	<center>
		<table>
			<thead>
				<tr>
					<td colspan='2'>AlertMail</td>
				</tr>
			</thead>
			<tr>
				<td class="td1">Mon_type</td>
				<td class="td2">${AM.monType}</td>
			</tr>
			<tr>
				<td class="td1">Alert_code</td>
				<td class="td2">${AM.alertCode}</td>
			</tr>
			<tr>
				<td class="td1">Alert_text</td>
				<td class="td2">${AM.alertText}</td>
			</tr>
			<tr>
				<td class="td1">Mon_date</td>
				<td class="td2">${AM.monDate}</td>
			</tr>
		</table>
	</center>
</body>
<html>
然后写一个加载ftl文件的JAVA类

import java.io.StringWriter;
import java.util.Map;

import com.service.impl.MonServiceImpl;

import freemarker.template.Configuration;
import freemarker.template.Template;

/*
 * use freemarker to send email
 */
public class FreemarkUtil {
	
	private static Configuration cfg;

	private static void initialConfig() {
		cfg = new Configuration();
		cfg.setClassForTemplateLoading(MonServiceImpl.class,
				"/package的名字,用'/'隔开/");
	}
	/*
	 * templateName means the ftl file name
	 * param means the Object used in ftl
	 */
	public static String getMail(String templateName,
			Map<String, Object> param) {
		String result = null;
		try {
			if (cfg == null) {
				initialConfig();
			}
			Template temp = cfg.getTemplate(templateName);
			StringWriter writer = new StringWriter();
			temp.process(param, writer);
			result = writer.toString();
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
然后在需要网ftl中输出内容的地方

paramMap.put("AM", a);  AM即FTL中的对象名,要一致
String mailContent = FreemarkUtil.getMail("FTL文件的名字.ftl",
						paramMap);
				mail.setContent(mailContent);
通过以上语句就可以是实现了。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值