由于jboss和tomcat容器的加载有些不同,具体的也说不清楚。总之就是获取类加载路径并不是真正的路径
public class FTLUtil{
//用freemarker的方式生成xml
public static String builXmlWithFreemarker(Map map, String fileName) {
String path = FTLUtil.class.getResource("/").getFile().toString().substring(1)+"ftl";
StringWriter out = new StringWriter();
try
{
Configuration configuration = new Configuration();
//
/**
* String path = "*********";
* 设置.ftl文件路径,可采用三种方式,由于jboss容器加载方式特殊,不能采用
* configuration.setDirectoryForTemplateLoading(new File(path));
* 需要采用:
* configuration.setClassForTemplateLoading(WechatStagingUtil.class, "/path");
*/
// configuration.setDirectoryForTemplateLoading(new File(path));
configuration.setClassForTemplateLoading(WechatStagingUtil.class, "/ftl");
Template template = configuration.getTemplate(fileName);
template.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
template.setEncoding("UTF-8");
template.setOutputEncoding("UTF-8");
Environment env = template.createProcessingEnvironment(map, out);
env.process();
out.flush();
}
catch (Exception e){
}finally{
try{
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
return out.toString();
}
采用第一种加载ftl文件路径的形式,输出出来的路径类似是:
/jboss-as-7.1.1.Final/modules/sun/jdk/main/service-loader-resources/ftl
并不是项目ftl文件的真正路径,这应该与启动服务时,不会把war包加载包出来有关。
采用下边的加载方法就可以正常把resources/ftl路径下的*.ftl文件加载出来:
configuration.setClassForTemplateLoading(FTLUtil.class, "/ftl");
博客主要讲述了JBoss和Tomcat容器加载的不同,导致获取类加载路径并非真正路径。以FreeMarker生成XML为例,采用常规方式设置.ftl文件路径在JBoss容器中无法正常加载,而使用configuration.setClassForTemplateLoading方法可正常加载resources/ftl路径下的.ftl文件。

9099

被折叠的 条评论
为什么被折叠?



