FreeMarker
FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。
一、引入依赖
eclipse
默认提供了 freemarker
依赖 org.eclipse.tools.templates.freemarker
。打开 plugin.xml
, 切换到 dependencies
页面, 将其加入依赖。如下图:
二、初始画 Freemarker
配置
编码人员通常都有良好编码习惯,比如习惯性地把项目中的模板文件放在统一的文件夹中,如此会使得Freemarker
配置代码更加简单优雅。好习惯对代码质量起到了积极的作用。
2.1 自定义配置类
在一个app应用中一般需要一套配置就可以了,因此以单例模式设计并实现 freemarker
全局配置类。
FreemarkerConfig
package com.xzbd.rcp02.config;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFile;
import com.xzbd.rcp02.exception.AppBaseException;
import com.xzbd.rcp02.util.WorkbenchUtil;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;
public class FreemarkerConfig {
private static Configuration cfiguration;
public static final String TMP_PATH = "/resources/templates";
private FreemarkerConfig() {
}
/**
* <h1>获取模板</h1>
* @param filePath 模板相对路径,相对于{@code TMP_PATH},如a/b/c.ftl 实际路径为:${TMP_PATH}/a/b/c.ftl。即:/resources/templates/a/b/c.ftl
* @return
*/
public static Template getTemplate(String filePath) {
Template tmp = null;
if(StringUtils.isBlank(filePath)) {
throw new AppBaseException("模板未找到,模板文件名为空");
}
if(Objects.isNull(cfiguration)) {
throw new AppBaseException("模板引擎未初始化");
}
try {
tmp = cfiguration.getTemplate(filePath);
} catch (Exception e) {
throw new AppBaseException("获取模板失败,输入:" + filePath);
}
return tmp;
}
public static void init() {
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
cfg.setDefaultEncoding("GBK");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
IFile tmpFile = WorkbenchUtil.getWorkSpaceFile(TMP_PATH);
File tmpPath = WorkbenchUtil.getLocalSystemPath(tmpFile.getFullPath());
if (!tmpPath.exists()) {
throw new AppBaseException("配置文件不存在");
}
cfg.setDirectoryForTemplateLoading(tmpPath);
cfg.setStrictSyntaxMode(true);
cfiguration = cfg;
} catch (Exception e) {
throw new AppBaseException("freemarker配置 初始化失败" + (StringUtils.isBlank(e.getMessage())? "": "\r\n" + e.getMessage()));
}
}
}
2.2 初始化配置
根据设计,在应用启动成功后初始化配置,因此在类 ApplicationWorkbenchAdvisor
的 postStartup
方法中调用FreemarkerConfig.init
方法 。代码如下:
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
//省略 ……
@Override
public void postStartup() {
try {
// 初始化模板引擎配置
FreemarkerConfig.init();
}catch (Exception e) {
e.printStackTrace();
}
}
//省略 ……
}
三、定义模板文件
根据配置类,freemarker
的模板文件放在 /resources/templates
文件夹下,其结构如下:
其中 test.ftl
文件内容如下:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
注意: 如果打包后的app安装目录中没有 resource
及其内部模板文件,请自行想办法将其复制到结果目录。这个很重要,也很容易忽略。如果程序报找不到模板文件,请在此处着手
四、使用 freemarker
生成代码
核心代码
// 组织模板数据
Map<String,Object> root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
// 获取模板 ,freemarker 或找到 /resources/templates/test.ftl 模板文件
Template template = FreemarkerConfig.getTemplate("test.ftl");
// 定义输出流,
Writer out = new OutputStreamWriter(new FileOutputStream("test.txt"), "utf-8");
// 调用引擎生成文件
template.process(functionLib, out);
out.flush();
if (out != null) {
out.close();
}
生成结果
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
<a href="products/greenmouse.html">green mouse</a>!
</body>
</html>
附
AppBaseException
package com.xzbd.rcp02.exception;
import org.apache.commons.lang.StringUtils;
public class AppBaseException extends RuntimeException {
private static final String DEFAULT_MESSAGE = "系统异常";
public AppBaseException() {
super(DEFAULT_MESSAGE);
}
public AppBaseException(String message) {
super(StringUtils.isNotBlank(message) ? message : DEFAULT_MESSAGE);
}
}
WorkbenchUtil
package com.xzbd.rcp02.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.ErrorEditorPart;
import org.eclipse.ui.part.FileEditorInput;
public class WorkbenchUtil {
public final static String GUID_REGEX_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
/**
* 获取工作空间
*
* @return
*/
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
/**
* 获取根工作空间
*
* @return
*/
public static IWorkspaceRoot getWorkspaceRoot() {
return getWorkspace().getRoot();
}
/**
* 获取工作空间中的文件
*
* @param filePath
* @return
*/
public static IFile getWorkSpaceFile(String filePath) {
return getWorkSpaceFile(new Path(filePath));
}
/**
* 获取工作空间中的文件
*
* @param filePath 文件路径
* @return
*/
public static IFile getWorkSpaceFile(IPath filePath) {
return getWorkspaceRoot().getFile(filePath);
}
/**
* 根据Eclipse虚拟路径获取系统资源路径
*
* @param path Eclipse虚拟路径
* @return
*/
public static File getLocalSystemPath(IPath path) {
// return getWorkspaceRoot().getLocation().append(path).toFile();
return getLocalSystemPath(path.toString());
}
/**
* 根据Eclipse虚拟路径获取系统资源路径
*
* @param path Eclipse虚拟路径 (相对路径)
* @return
*/
public static File getLocalSystemPath(String path) {
// return getWorkspaceRoot().getLocation().append(path).toFile();
return new File(getWorkspaceRoot().getLocation().toFile().getParentFile().toString() + "\\" + path);
}
总结
以上就是 Eclipse插件中整合 FreeMarker 的所有内容,有不周之处,欢迎留言指正。