Velocity在web项目中生成模板

来源:互联网 发布:discuz数据库备份 编辑:程序博客网 时间:2024/06/06 08:27

需求:后台(指管理员后台)上传一个html模板到文件服务器上,前台(商家操作的平台)读取到模板,并填充数据,生成新的vm页面到webapp/WEB-INF/view目录下,用于预览、保存、打印。


最开始的代码:

        @Testpublic void test() throws Exception{String templateUrl = baseService.getPicServerURL()+"group1/M00/02/1E/wKi0d1NasvaAF6x_AAAdoyBssxg53.html";//初始化模板Template template = Velocity.getTemplate(templateUrl,"UTF-8");//初始化上下文VelocityContext context = new VelocityContext();//添加数据到上下文中context.put("title","我的第一个velocity模板生成页面");//生成html页面PrintWriter pw = new PrintWriter("webapp/WEB-INF/view/center/dm_manage/test.htm");template.merge(context,pw);//关闭流pw.close();}

以上标红色部分为错误的地方:

错误信息:Unable to find velocity template resources

出现的原因:我的模板在文件服务器上, Velocity.getTemplate()方法没办法直接解析到服务器上的文件,对于这个问题有三种想法:

1.直接在后台上传文件的时候,上传到web服务器中,弊端:服务器重启后数据会丢失,PASS.

2.用HTMLParser解析html模板,替换里面的值,再生成新的vm页面,弊端:太过复杂,PASS.

3.从服务器上下载html,再写到项目的某个目录中,Velocity.getTemplate()方法就可解析到,WORK。

方案3的完整代码:

//将byte数组写入文件      public void createFile(String path, byte[] content) throws IOException {          FileOutputStream fos = new FileOutputStream(path);          fos.write(content);          fos.close();      }  @Testpublic void createNewFile() throws Exception{byte[] content = fileService.downloadFile("M00/02/1E/wKi0d1NasvaAF6x_AAAdoyBssxg53.html");String path = "src/main/resources/dm-template/wKi0d1NasvaAF6x_AAAdoyBssxg53.html";File f = new File(path);if(!f.exists()){createFile(path, content);}}
  @Testpublic void test() throws Exception{  Properties p = new Properties();p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "src/main/resources/dm-template/");Velocity.init(p);//初始化模板Template template = Velocity.getTemplate("wKi0d1NasvaAF6x_AAAdoyBssxg53.html","UTF-8");//Template template = ve.getTemplate("group1/M00/02/1E/wKi0d1NasvaAF6x_AAAdoyBssxg53.html","UTF-8");//初始化上下文VelocityContext context = new VelocityContext();//添加数据到上下文中context.put("title","我的第一个velocity模板生成页面123test");//生成html页面PrintWriter pw = new PrintWriter("src/main/webapp/WEB-INF/view/center/dm_manage/test.htm");template.merge(context,pw);//关闭流pw.close();}

0 0
原创粉丝点击