jboss服务器读取freemarker文件问题解决方案

博客主要讲述了JBoss和Tomcat容器加载的不同,导致获取类加载路径并非真正路径。以FreeMarker生成XML为例,采用常规方式设置.ftl文件路径在JBoss容器中无法正常加载,而使用configuration.setClassForTemplateLoading方法可正常加载resources/ftl路径下的.ftl文件。

由于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");

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值