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"%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值