首先,曾经天真的觉得freemarker跟jstl和el同样,只是显示数据用的标签。可是实际上freemarker数据jsp级别的,能够用来生成静态页面。html
先来看看freemarker在页面上是如何被调用的。java
public class FreeMarkHander { private Configuration cfg; // 模版配置对象 public void init(String templatePath) throws Exception { // 初始化FreeMarker配置 // 建立一个Configuration实例 cfg = new Configuration(Configuration.VERSION_2_3_21); // 设置FreeMarker的模版文件夹位置 //String templatePath = request.getSession().getServletContext().getRealPath("/template"); cfg.setDirectoryForTemplateLoading(new File(templatePath)); // 设置异常处理器 cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setDefaultEncoding("utf-8"); } public String process(Map<String, Object> map, String ftl) throws Exception { String rtn = ""; Template tpl = cfg.getTemplate(ftl); ByteOutputStream stream = new ByteOutputStream(); Writer out = new OutputStreamWriter(stream); tpl.process(map, out); out.flush(); rtn = stream.toString(); return rtn; } /**** * 数据渲染html片断 * @param map 填充数据 * @param templatePath 模板路径 * @param ftlName 模板名称 * @return html片断字符串 * @throws Exception */ public static String createPage(Map<String, Object> map,String templatePath,String ftlName)throws Exception { String html = ""; FreeMarkHander fh = new FreeMarkHander(); fh.init(templatePath); html = fh.process(map,ftlName); return html; }
第一个方法,初始化模板的配置,包括模板所在文件夹的位置,规定编码方式等等。jsp
最下面createPage方法是在jsp上调用的,传入的map即为传入的数据集合,templatePath是模板文件夹在项目的绝对路径,ftlName则是具体模板的名称。中间调用的process本身体会了(没有异常抓取等等,凑合用)编码
模板的所在的文件夹能够本身设立,本项目中在WebRoot下的template中。spa
模板的具体长相:code
<#if newList?size gt 0> <div class="list"> <ul> <#list newList as news> <li id="${news.news_id}" name="news_list"><a href="${news.news_id?default('')}" target="_blank" title="${news.title?default('')}"><i class="icon icon-arrow"></i><span>${news.title?default('')}</span></a></li> </#list> </ul> </div> <div class="more"><a id="the_more_news">更多 <i class="icon icon-arrow-double"> </i></a></div> <#else > <div class="list empty"> <div class="page-message-empty"> <div class="mascot cry"><i class="icon icon-none-cry"></i> <div class="message">没有相关资讯</div> </div> </div> </div> </#if>
在jsp中的写法:htm
NewsService newService = new NewsServiceImpl(); List<News> newList = newService.newsList(org_id, dataSource);//获取须要渲染的数据 map.put("newList",newList);//装进map String str = FreeMarkHander.createPage(map, templatePath, "news.ftl");//将数据扔进模板渲染
最后,在页面上须要的位置对象
<%=str%>
就OK了。utf-8
ps:freemarker上没法写java代码,能够实现真正的v_c层的分离。字符串