使用freemarker和spring构造模板

问题描述 投票:1回答:2

我是freemarker的新手。我有一个计划与freemarker一起使用的spring应用程序。模板将存储在数据库中,并基于登录名,我想从数据库中检索模板。谁能告诉我在构造模板后如何在春季配置freemarker并获取html标签作为字符串。我做了谷歌搜索,但我听不懂。

我一直尝试到这个水平。在春季,我已经做到了这一水平。最后,我想要字符串中的html标签。

// Spring freemarker specific code
Configuration configuration = freemarkerConfig.getConfiguration();
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// My application specific code
String temp = tempLoader.getTemplateForCurrentLogin();

谢谢。

java spring freemarker
2个回答
2
投票
// you already have this bit String templateText = tempLoader.getTemplateForCurrentLogin(); // now programmatically instantiate a template Template t = new Template("t", new StringReader(templateText), new Configuration()); // now use the Spring utility class to process it into a string // myData is your data model String output = FreeMarkerTemplateUtils.processTemplateIntoString(template, myData);

1
投票
public static String processFreemarkerTemplate(String fileName) { StringWriter stringWriter = new StringWriter(); Map<String, Object> objectMap = new HashMap<>(); Configuration cfg = new Configuration(Configuration.VERSION_2_3_24); try { cfg.setDirectoryForTemplateLoading(new File("path/of/freemarker/template")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); Template template = cfg.getTemplate(fileName); template.process(objectMap, stringWriter); } catch (IOException | TemplateException e) { e.printStackTrace(); } finally { if (stringWriter != null) { try { stringWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } return stringWriter.toString(); }
© www.soinside.com 2019 - 2024. All rights reserved.