Freemarker静态页面

简介

FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件配置文件源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

FreeMarker是免费的,基于Apache许可证2.0版本发布。其模板编写为FreeMarker Template Language(FTL),属于简单、专用的语言。需要准备数据在真实编程语言中来显示,比如数据库查询和业务运算, 之后模板显示已经准备好的数据。在模板中,主要用于如何展现数据, 而在模板之外注意于要展示什么数据   。

使用

1、 安装 freemarker eclipse 编辑插件  

       将 “freemarker_eclipseplugin” 复制  eclipse 的 dropins 文件夹 ,重启开发工具 

2、 编辑 freemarker 的模板文件  

       通常模板文件 放在 WEB-INF 下 或者 classes 下 

3、 编写测试代码 

public String showDetail() throws Exception {
		// 先判断 id 对应html 是否存在,如果存在 直接返回
		String htmlRealPath = ServletActionContext.getServletContext()
				.getRealPath("/freemarker");
		File htmlFile = new File(htmlRealPath + "/" + model.getId() + ".html");

		// 如果html文件不存在 ,查询数据库,结合freemarker模板生成 页面
		if (!htmlFile.exists()) {
			Configuration configuration = new Configuration(
					Configuration.VERSION_2_3_22);
			configuration.setDirectoryForTemplateLoading(new File(
					ServletActionContext.getServletContext().getRealPath(
							"/WEB-INF/freemarker_templates")));
			// 获取模板对象
			Template template = configuration
					.getTemplate("promotion_detail.ftl");

			// 动态数据
			Promotion promotion = WebClient
					.create(Constants.BOS_MANAGEMENT_URL
							+ "/bos_management/services/promotionService/promotion/"
							+ model.getId()).accept(MediaType.APPLICATION_JSON)
					.get(Promotion.class);
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("promotion", promotion);

			// 合并输出
			template.process(parameterMap, new OutputStreamWriter(
					new FileOutputStream(htmlFile), "utf-8"));

		}

		// 存在 ,直接将文件返回
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		FileUtils.copyFile(htmlFile, ServletActionContext.getResponse()
				.getOutputStream());

		return NONE;
	}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值