1. 程式人生 > >beetl學習根據URL生成模板

beetl學習根據URL生成模板

字符輸入 apr ner ioe .get catch muti puts ()

官方文檔: http://ibeetl.com/guide/#beetl

多謝beetl的作者抽空指點!!!

根據遠程文件服務器生成模板:

需要註意的是:

  • StringTemplateResourceLoader:字符串模板加載器,用於加載字符串模板,如本例所示(根據url讀取文件內容,然後根據這個對象生成Template對象)
  • FileResourceLoader:文件模板加載器,需要一個根目錄作為參數構造,傳入getTemplate方法的String是模板文件相對於Root目錄的相對路徑
  • ClasspathResourceLoader:文件模板加載器,模板文件位於Classpath裏
  • WebAppResourceLoader:用於webapp集成,假定模板根目錄就是WebRoot目錄,參考web集成章
  • MapResourceLoader : 可以動態存入模板
  • CompositeResourceLoader 混合使用多種加載方式
protected void generateFile(String template, String filePath) {
        if(template.indexOf("http") != -1) {

            try {
                //創建一個URL實例
                URL url = new URL("http://xxx/xxx/wKgUFFub3CmAer4pAAABjPGvkcI576.btl");
                
//通過URL的openStrean方法獲取URL對象所表示的自願字節輸入流 InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is,"utf-8"); //為字符輸入流添加緩沖 BufferedReader br = new BufferedReader(isr); String data = null;//讀取數據 StringBuffer sb = new
StringBuffer(); while ((data = br.readLine())!=null){//循環讀取數據 data += "\r\n"; sb.append(data); } br.close(); isr.close(); is.close(); StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader(); Configuration cfg = Configuration.defaultConfiguration(); GroupTemplate gt = new GroupTemplate(resourceLoader,cfg); Template pageTemplate = gt.getTemplate(sb.toString()); templateToFile(filePath, pageTemplate); } catch (IOException e) { e.printStackTrace(); } }else { Template pageTemplate = groupTemplate.getTemplate(template); templateToFile(filePath, pageTemplate); } } protected void templateToFile(String filePath, Template pageTemplate) { configTemplate(pageTemplate); if (PlatformUtil.isWindows()) { filePath = filePath.replaceAll("/+|\\\\+", "\\\\"); } else { filePath = filePath.replaceAll("/+|\\\\+", "/"); } File file = new File(filePath); File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); pageTemplate.renderTo(fileOutputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }

beetl學習根據URL生成模板