其中所用框架Spring,SpringMVC,Hibernate,freemarker
//首先要新建一个实现TemplateDirectiveModel接口的类
public class GettingGanonDirective implements TemplateDirectiveModel
//由于使用的hibernate4,所以自动注入的sessionFactory。
@Autowired
private SessionFactory sessionFactory;
要适用自定义标签,主要的就是实现execute方法
@Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody)
throws TemplateException, IOException {
/*(参数:
environment或env用到它的getOut()方法来得到Writer对象,
map或者params可以适用get("key")方法来得到在模板中使用自定义标签是传入的参数,
剩下俩还不晓得,TemplateDirectiveBody 好像是用来传对象到模板中
)*/
Writer out = environment.getOut();
//得到writer对象,作用相当于在servlet中响应ajax时候使用的writer
System.err.println(map+"size:"+map.size());
if (map.size()!=0&&map!=null) {
TemplateModel paramValue = (TemplateModel) map.get("channelId");
//取得key为channelId的参数值
if (paramValue.equals("") || paramValue != null) {
/*int channelId = Integer.parseInt("paramValue");*/
Session session = sessionFactory.getCurrentSession();
//通过注入的sessionFactory的getCurrentSession()方法获取当前线程下的Session对象
String sql = "SELECT t1.channel_id,t2.channel_name FROM jc_channel t1\n" +
"LEFT JOIN jc_channel_ext t2 \n" +
"ON t1.channel_id=t2.channel_id\n" +
"WHERE t1.channel_id = " + paramValue;
List list = session.createSQLQuery(sql).list();
StringBuffer stringBuffer = new StringBuffer();
ArrayList<String> arrayList=null;
for (Object object :list) {
Object[] objects = (Object[]) object;
/*for (Object object2:objects) {
System.err.println("取得的内容为:"+object2.toString());
}*/
String[] strings = new String[2];
for (int i = 0; i < strings.length ; i++) {
strings[i] = objects[i].toString();
}
stringBuffer.append("栏目ID:"+objects[0].toString()+"</br>栏目名称:"+objects[1]);
}
System.err.println(arrayList);
System.err.println(stringBuffer.toString());
out.write(stringBuffer.toString());
//最终,通过Writer对象的write()方法将查询到的值输出到模板中
} else {
out.write("参数异常,找不到目标id");
}
}else{
out.write("无参数,请确认自定义宏参数有效!");
}
}
<!--
测试用标签
-->
< beanid="dz_getChannel"class="com.jeecms.cms.action.directive.testForDz.GettingGanonDirective"/>
property中
directive.dz_getChannel = dz_getChannel
在Spring配置文件中获取标签配置,并引入相应peoperty的值。
<propertyname="freemarkerVariables"value="#{propertyUtils.getBeanMap('directive.')}"/>
在模板中引入自定义的标签
[@dz_getChannel channelId='75'][/@dz_getChannel]
直接加载模板,控制台输出:
栏目ID:75</br>栏目名称:新闻
页面效果: