java 使用Freemarker 生成html

 

1、定义模板,模板中的变量就是程序需要set的值。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
<script type="text/javascript">
function doSubmit(){
document.getElementById("form1").submit();
}
</script>
</head> 
<body οnlοad="doSubmit()">
<form id="form1" method="post" action="${url}" >
<#list weaponMap?keys as key> 
<input type="hidden" name="${key}" value="${weaponMap[key]!("null")}"/>
</#list> 
</form>
</body> 
</html>

  

 

2、java代码实现 

private Configuration freemarke_cfg = null;

	public static void main(String agrs []) throws Exception {

		String path = FreemarkerTest.class.getResource("/").getPath();
		FreemarkerTest test = new FreemarkerTest();

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("url", "http://www.baidu.com");

		// map 集合 循环的
		Map<String, Object> weaponMap = new HashMap<String, Object>();
		weaponMap.put("data", "1");
		weaponMap.put("code", "00");
		weaponMap.put("message", "成功");
		paramMap.put("weaponMap", weaponMap);

		test.geneHtmlFile(path, "template", paramMap, path, "tempFileName");
	}

	protected Configuration getFreeMarkerCFG(String sTemplateFilePath) {

		if (null == freemarke_cfg) {
			freemarke_cfg = new Configuration();
			freemarke_cfg.setEncoding(Locale.CHINA, "UTF-8");
			// 基于类路径的模版加载器
			freemarke_cfg.setClassForTemplateLoading(this.getClass(),
					"/websiteroot/freemarker");
			try {
				freemarke_cfg.setDirectoryForTemplateLoading(new File(
						sTemplateFilePath));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return freemarke_cfg;
	}

	/**
	 * 生成静态文件
	 *
	 * @param templatePath
	 *            :模板路径
	 * @param templateFileName
	 *            :模板名称
	 * @param propMap
	 *            :存放数据模型的Map
	 * @param htmlFilePath
	 *            :生成HTML页面的存放路径
	 * @param htmlFileName
	 *            :生成html页面的名称
	 * */
	public boolean geneHtmlFile(String templatePath, String templateFileName,
			Map<String, Object> propMap, String htmlFilePath,
			String htmlFileName) {
		try {
			Template t = getFreeMarkerCFG(templatePath).getTemplate(
					templateFileName);
			t.setEncoding("UTF-8");
			creatDirs(htmlFilePath);
			File afile = new File(htmlFilePath + "/" + htmlFileName);

			// 设置生成的文件编码为UTF-8
			// 服务器不支持UTF-8格式HTML时候使用ANSI格式HTML文件,即系统默认编码
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(afile), "UTF-8"));
			t.process(propMap, out);
		} catch (IOException e) {
			logger.error("Error " + htmlFileName, e);
			return false;
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	

	public static boolean creatDirs(String path) {
		File aFile = new File(path);
		if (!aFile.exists()) {
			return aFile.mkdirs();
		} else {
			return true;
		}
	}

  

3、最终会生成一个 tempFileName 的文件。在项目的target\classes 路径下面。成功后会有如下展示

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Insert title here</title>  
	<script type="text/javascript">
    	function doSubmit(){
    		document.getElementById("form1").submit();
    	}
	</script>
</head>  
<body οnlοad="doSubmit()">
	 <form id="form1" method="post" action="http://www.baidu.com" >
	    <input type="hidden" name="message" value="成功"/>
	    <input type="hidden" name="data" value="1"/>
	    <input type="hidden" name="code" value="00"/>
     </form>
</body>  
</html>  

  

4、所需要的jar包

需要jar包

<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.16</version>
</dependency>

 

如有疑问可以找我!

转载于:https://www.cnblogs.com/wangjiesheng/p/7093993.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值