Java 使用freemarker和spring构建模板
我对freemarker是新手。我有一个spring应用程序,我计划与freemarker一起使用。模板将存储在数据库中,基于登录,我想从数据库中检索模板。有人能告诉我如何在spring中配置freemarker,并在构建模板后将html标记作为字符串获取吗。我在谷歌上搜索过,但我不太懂 我一直试到这个水平。在春天,我已经做到了这个水平。最后,我想要一个字符串中的html标记Java 使用freemarker和spring构建模板,java,spring,freemarker,Java,Spring,Freemarker,我对freemarker是新手。我有一个spring应用程序,我计划与freemarker一起使用。模板将存储在数据库中,基于登录,我想从数据库中检索模板。有人能告诉我如何在spring中配置freemarker,并在构建模板后将html标记作为字符串获取吗。我在谷歌上搜索过,但我不太懂 我一直试到这个水平。在春天,我已经做到了这个水平。最后,我想要一个字符串中的html标记 // Spring freemarker specific code Configuration configurati
// Spring freemarker specific code
Configuration configuration = freemarkerConfig.getConfiguration();
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// My application specific code
String temp = tempLoader.getTemplateForCurrentLogin();
谢谢。要将您发布的代码绑定在一起,您可以执行以下操作:
// 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);
此java方法将处理freemarker模板,并在构建模板后将html标记作为字符串提供
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();
}
公共静态字符串处理器FreeMarkerTemplate(字符串文件名){
StringWriter StringWriter=新StringWriter();
Map objectMap=newhashmap();
配置cfg=新配置(配置.版本2\u 3\u 24);
试一试{
setdirectoryforemplateLoading(新文件(“path/of/freemarker/template”);
设置默认编码(“UTF-8”);
setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW\u HANDLER);
setLogTemplateExceptions(false);
模板模板=cfg.getTemplate(文件名);
流程(objectMap、stringWriter);
}捕获(IOException | TemplateException e){
e、 printStackTrace();
}最后{
if(stringWriter!=null){
试一试{
stringWriter.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
返回stringWriter.toString();
}