项目是SpringBoot + Freemarker的。
所有的页面都是Freemarker文件写的,有些页面数据比较多,打开比较慢,所以做了一个静态页面。
因为本身所有的页面都是FTL文件,所以模板就地取材,不用自己另外去写。
核心处理spring.ftl文件中的内容就可以了。
spring.ftl文件中都是以springMacroRequestContext对象来处理的。只要找到这个对象的值是从那里来的就行了。
AbstractTemplateView类中:
关键部分代码:
Map<String, Object> ftlMap = new HashMap<String, Object>(); ftlMap.put(AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, new RequestContext(request, response, request.getServletContext(), null)); ftlMap.put("model", "需要填充的数据,数据类型可以是map,model类等"); String ftlPath = "模板.ftl", htmlPath = "静态文件.html"); boolean cr = FreemarkerUtil.createHtml(ftlMap, ftlPath, htmlPath);
其中request和response:
HttpServletRequest request, HttpServletResponse response
FreemarkerUtil代码:
public class FreemarkerUtil { public static String ENCODING = "UTF-8"; public static String LOCATION_PATH = FileUtil.LOCATION_PATH; public static String FTL_ROOT_PATH = "/templates"; private static Configuration configuration = new Configuration(Configuration.VERSION_2_3_22); static { configuration.setDefaultEncoding(ENCODING); // 设置模板装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载。 // 加载模板文件,放src/main/resources在下 configuration.setClassForTemplateLoading(FreemarkerUtil.class, FTL_ROOT_PATH); // 设置异常处理器 configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); } public static boolean createHtml(Map<String, Object> dataMap, String ftlPath, String htmlPath) { boolean r = false; try { // 加载需要装填的模板 Template template = null; // 定义Template对象 template = configuration.getTemplate(ftlPath); String filePath = LOCATION_PATH + File.separator + htmlPath; File outFile = new File(filePath); Writer out = null; out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), ENCODING)); template.process(dataMap, out); out.close(); r = true; } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } return r; } }
ftl页面既可以使用动态的,也可以是用静态的,根据自己的业务逻辑处理。
作者:Se7end
声明:本博客文章为原创,只代表本人在工作学习中某一时间内总结的观点或结论。转载时请在文章页面明显位置给出原文链接。