都知道FreeMarker加载模板文件有以下三种方式:
1、从文件目录加载
2、从类路径加载
3、从Servlet上下文加载
其中第二个和第三个常用在Web开发环境中,类路径也会使用在普通的Java Project中,不限制开发环境。
本文主要说明如果模板文件不是和应用程序放在同一台主机上,那么如何去读取和解析这些模板文件呢?答案是可以解决的,FreeMarker就提供给
我们一种加载模板的方式,查看API就有URLTemplateLoader类,该类为抽象类,从名字就可以看出从给定的URL加载模板文件,这个URL并没有限定来源,
说明可以是其他各个地方的来源:FTP服务器,Hadoop,db等等。那么可以自定义个加载器,从这个类继承,实现里面的getUrl方法即可:
[java] view plain copy /** * */ package com.XX.XX.freemarker; import java.net.MalformedURLException; import java.net.URL; import freemarker.cache.URLTemplateLoader; /** * 自定义远程模板加载器,用来加载远程机器上存放的模板文件,比如FTP,Handoop等上的模板文件 * @author Administrator * */ public class RemoteTemplateLoader extends URLTemplateLoader { //远程模板文件的存储路径(目录) private String remotePath; 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 protected URL getURL(String name) { String fullPath = this.remotePath + name; if ((this.remotePath.equals("/")) && (!isSchemeless(fullPath))) { return null; } if (this.remotePath.indexOf("streamFile") == -1 && this.remotePath.indexOf("webhdfs") != -1)//这个是针对不直接使用文件流形式进行访问和读取文件而使用的格式 { fullPath = fullPath + "?op=OPEN"; } 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; } }转载于:https://www.cnblogs.com/scwanglijun/p/4010945.html