扩展:FreeMarker渲染引擎

  1. /**
  2. * Freemarker 渲染器
  3. * @version : 2016年1月3日
  4. * @author 赵永春 (zyc@hasor.net)
  5. */
  6. @Render("flt")
  7. public class FreemarkerRender implements RenderEngine {
  8. protected Configuration freemarker;
  9. //
  10. /** 内置创建 Freemarker 对象的方法,您也可以通过 apiBinder.bind(Configuration.class).... 来设置您自定义的。 */
  11. protected Configuration newConfiguration(AppContext appContext, ServletContext servletContext) throws IOException {
  12. //
  13. String realPath = servletContext.getRealPath("/");
  14. TemplateLoader templateLoader = new FileTemplateLoader(new File(realPath), true);
  15. Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
  16. configuration.setTemplateLoader(templateLoader);
  17. //
  18. String responseEncoding = appContext.findBindingBean(RuntimeFilter.HTTP_RESPONSE_ENCODING_KEY, String.class);
  19. if (StringUtils.isBlank(responseEncoding)) {
  20. responseEncoding = Settings.DefaultCharset;
  21. }
  22. configuration.setDefaultEncoding(responseEncoding);
  23. configuration.setOutputEncoding(responseEncoding);
  24. configuration.setLocalizedLookup(false);//是否开启国际化false
  25. configuration.setClassicCompatible(true);//null值测处理配置
  26. //
  27. return configuration;
  28. }
  29. /** 各种工具&变量 */
  30. protected void configSharedVariable(AppContext appContext, ServletContext servletContext, Configuration freemarker) throws TemplateModelException {
  31. freemarker.setSharedVariable("stringUtils", new StringUtils());
  32. freemarker.setSharedVariable("ctx_path", servletContext.getContextPath());
  33. }
  34. public void initEngine(AppContext appContext) throws Throwable {
  35. ServletContext servletContext = Hasor.assertIsNotNull(appContext.getInstance(ServletContext.class));
  36. BindInfo<Configuration> bindInfo = appContext.getBindInfo(Configuration.class);
  37. if (bindInfo == null) {
  38. this.freemarker = this.newConfiguration(appContext, servletContext);
  39. } else {
  40. this.freemarker = appContext.getInstance(bindInfo);
  41. }
  42. this.configSharedVariable(appContext, servletContext, Hasor.assertIsNotNull(this.freemarker));
  43. }
  44. public boolean exist(String template) throws IOException {
  45. return this.freemarker.getTemplateLoader().findTemplateSource(template) != null;
  46. }
  47. public void process(RenderInvoker renderData, Writer writer) throws Throwable {
  48. Template temp = this.freemarker.getTemplate(renderData.renderTo());
  49. if (temp == null) {
  50. return;
  51. }
  52. HashMap<String, Object> data = new HashMap<>();
  53. for (String key : renderData.keySet()) {
  54. data.put(key, renderData.get(key));
  55. }
  56. temp.process(data, writer);
  57. }
  58. }