elicer 发表于 2013-2-3 14:19:34

FreeMarker 真实案例应用

定义模板

这个模板很简单,就是定义了一个显示文章的指今,然在的显示最新文章和热门文章的时候调用即可

模板文件源代码:
<#macro showNewArticles articles>    <#list articles as article>      <li>      ${article_index+1}.      <a target="_blank" href="/article/${article.id }">${article.title }</a>    </li>    </#list></#macro><%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%><link rel="stylesheet" type="text/css" href="/resources/css/foot.css" /><div id="footer_area">    <div id="footer_area_content">    <div class="box">            <h3>最近发布</h3>      <div class="box_content">      <ol>                <@showNewArticles articles=newDESCArticles />      </ol>      </div>    </div>      <div class="box">      <h3>热门文章</h3>      <div class="box_content">                <ol>                <@showNewArticles articles=viewCountDescArticles />            </ol>      </div>    </div>    <!-- 省略了一部分 -->    </div></div>


Freemarker的服务类

freemarker服务类会调用articleService

完整源代码:

package com.naxsu.service;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.naxsu.entity.Article;import com.naxsu.utils.FreemarkerUtil;@Service("freemarkerService")public class FreeMarkerService {    @Resource(name="articleService")    private ArticleService articleservice;                public void getFootPage() {    Map<String,Object> root = new HashMap<String,Object>();    List<Article> newDESCArticles = articleservice.getNewDESCArticle();    List<Article> viewCountDescArticles = articleservice.getViewCountDESCArticle();    root.put("newDESCArticles", newDESCArticles);    root.put("viewCountDescArticles", viewCountDescArticles);            String path =this.getClass().getProtectionDomain()                           .getCodeSource().getLocation().getPath();    path = path.substring(0,path.indexOf("/WEB-INF"));    FreemarkerUtil.getInstance().fprint("foot.ftl", root,                      path+"/WEB-INF/jsp/template/foot.jsp");    }      }


用spring aop实现切面拦截文章的增删改的服务

在增删改文章的时候都会调用freemarkerService,从而生成相应的jsp。FreeMarker与SpringMVC整合在这里不做多说,请看相关的文章。

源代码如下:
<aop:config>    <aop:aspect ref="freemarkerService">    <aop:pointcut id="createFootTemplate"      expression="execution(* com.naxsu.service.ArticleService.insert*(..))||      execution(* com.naxsu.service.ArticleService.update*(..))||      execution(* com.naxsu.service.ArticleService.delete*(..))"/>    <aop:after method="getFootPage" arg-names="id" pointcut-ref="createFootTemplate"/>    </aop:aspect></aop:config>

jsp的嵌入

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="../template/foot.jsp"%>
页: [1]
查看完整版本: FreeMarker 真实案例应用