利用freemarker、java生成html静态页面

本文详细介绍了如何通过Freemarker和Java实现生成静态页面的过程,包括核心代码的实现和关键步骤解析,适用于网页开发领域的开发者。

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

这几天在搞一个利用freemarker和java生成静态页面的东西,经过百度和自己的调试终于搞定,现在总结出核心代码分享。

 

/**
	 * 生成静态页面主方法
	 * 
	 * @param context
	 *            ServletContext
	 * @param data
	 *            一个Map的数据结果集
	 * @param templatePath
	 *            ftl模版路径
	 * @param targetHtmlPath
	 *            生成静态页面的路径
	 */
	public static void crateHTML(ServletContext context,
			Map<String, Object> data, String templatePath, String targetHtmlPath) {
		// 加载模版
		freemarkerCfg.setServletContextForTemplateLoading(context, "/");
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
		String filePath = ServletActionContext.getServletContext().getRealPath(
				"/static");
		File file = new File(filePath);
		if(!file.exists() || !file.isDirectory()){
			file.mkdir();
		}
		File f = new File(file,"/all_css");
		if(!f.exists() || !f.isDirectory()){
			f.mkdir();
		}
		try {
			freemarkerCfg.setDirectoryForTemplateLoading(new File(filePath));
			// 设置包装器,并将对象包装为数据模型
			freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
			// 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
			// 否则会出现乱码
			Template template = freemarkerCfg
					.getTemplate(templatePath, "UTF-8");
			template.setEncoding("UTF-8");
			// 静态页面路径
			String htmlPath = filePath + "/" + targetHtmlPath;
			File htmlFile = new File(htmlPath);
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(htmlFile), "UTF-8"));
			// 处理模版
			template.process(data, out);
			out.flush();
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 生成友情链接的静态页cuxiao.html
	 * 
	 * @param context
	 * @param data
	 */
	public static void createIndexFriendLink(ServletContext context,
			Map<String, Object> data) {
		try {
		//cuxiao.ftl是项目中建立的ftl文件,cuxiao.html是生成的静态页面名
			return crateHTML(context, data, "/cuxiao.ftl", "cuxiao.html");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
 

   最后调用方法,private Map<String, Object> pList = new HashMap<String, Object>();

List list = new ArrayList();
pList.put("list",list);
HttpServletRequest request = ServletActionContext.getRequest();
			pList.put("JspTaglibs", new TaglibFactory(request.getSession()
					.getServletContext()));
			 this.createIndexFriendLink(
					ServletActionContext.getServletContext(), pList);
//页面介绍map时一定要与pList中的key一致
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值