FreeMarer 模板加载,使用FreeMarker加载远程主机上模板文件

FreeMarer 模板加载,使用FreeMarker加载远程主机上模板文件

FreeMarker加载模板文件的三种方式:

1、从文件目录加载

2、从类路径加载

3、从Servlet上下文加载

其中第二个和第三个常用在Web开发环境中,类路径也会使用在普通的Java Project中,

如果模板文件不是和应用程序放在同一台主机上,那么如何去读取和解析这些模板文件呢?答案是可以解决的,FreeMarker就提供给一种加载模板的方式,查看API就有URLTemplateLoader类,该类为抽象类,从名字就可以看出从给定的URL加载模板文件,这个URL并没有限定来源,

来源可实现从FTP服务器,Hadoop,db等等。那么可以自定义个加载器,从这个类继承,实现里面的getUrl方法即可:

/**
* 自定义远程模板加载器,用来加载远程机器上存放的模板文件.HTTP
*
* @author *
*
*/
public class RemoteTemplateLoader extends URLTemplateLoader {
// 远程模板文件的存储路径(目录)
private String remotePath;

private List<String> includePaths;

public RemoteTemplateLoader(String remotePath) {
if (remotePath == null) {
throw new IllegalArgumentException("remotePath is null");
}
this.remotePath = canonicalizePrefix(remotePath);
if (this.remotePath.indexOf('/') == 0) {
this.remotePath = this.remotePath.substring(this.remotePath.indexOf('/') + 1);
}
}

@Override
public Object findTemplateSource(String name) throws IOException {
if(this.includePaths!=null&&this.includePaths.contains(name)){
return super.findTemplateSource(name);
}
return null;

}

@Override
protected URL getURL(String name) {
// name = name.replace("_zh", "");
String fullPath = this.remotePath + name;
System.out.println(fullPath);
if ((this.remotePath.equals("/")) && (!isSchemeless(fullPath))) {
return null;
}

URL url = null;
try {
url = new URL(fullPath);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}

private static boolean isSchemeless(String fullPath) {
int i = 0;
int ln = fullPath.length();

if ((i < ln) && (fullPath.charAt(i) == '/'))
i++;

while (i < ln) {
char c = fullPath.charAt(i);
if (c == '/')
return true;
if (c == ':')
return false;
i++;
}
return true;
}

public void setRemotePath(String remotePath) {
this.remotePath = remotePath;
}

public List<String> getIncludePaths() {
return includePaths;
}

public void setIncludePaths(List<String> includePaths) {
this.includePaths = includePaths;
}
}

Spring MVC配置文件如下:

<!-- 针对free marker的视图 -->
<bean />
</bean>

<bean />

<!--设置远程加载路径-->

<property name="includePaths">
<list>
<value>footer.ftl</value>
<value>common/footer.ftl</value>
</list>
</property>
</bean>

<util:list />
</util:list>

<bean />
</bean>

需要注意的是:通过远程加载模板,FreeMarker没有check远程加载此文件是否存在,所以只能通过本地列表(includePaths)判断是否存在,加快模板加载速度。

                     另外也通过http和FTP方式判断此模板是否远程服务器存在,但考虑性能及文件加载数量(主要是加载一些公共头信息文件,文件数据量有限)

                     通过此扩展功能可实现(header.ftl、footer.ftl及公共模块的管理),在项目中可实现多个WEB网络实现统一的管理。