所需jar包
freemarker.jar、gson.jar(操作json串)
ftl模板文件(header.ftl),路径为“webroot/templates”目录下
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>联系人</title>
</head>
<body>
<script src="/jeesite/assets/global/plugins/jquery.min.js"></script>
<div><h2>WELCOME,${user}。欢迎登录!</h2></div>
<div>Modifier:${modifier}</div>
<div>pass:${pass}</div>
</body>
</html>
自定义标签java类(getFtlTemplateTag.java)
package com.test.freemarker.common;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import com.google.l99gson.Gson;
import com.google.l99gson.reflect.TypeToken;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class getFtlTemplateTag extends TagSupport{
private static final long serialVersionUID = 1577211372616750949L;
private String fileName = null;
private String parmsStr = null;
public void setFileName(String fileName){
this.fileName = fileName;
}
public void setParmsStr(String paramsStr) {
this.parmsStr = paramsStr;
}
@SuppressWarnings("unused")
private Map<String, String> setParams(){
Gson gson = new Gson();
return gson.fromJson(parmsStr, new TypeToken<Map<String, String>>() {}.getType());
}
@Override
public int doStartTag() throws JspException {
JspWriter out = this.pageContext.getOut();
Configuration conf = new Configuration();
//conf.setClassForTemplateLoading(this.getClass(), "template");
conf.setServletContextForTemplateLoading(pageContext.getServletContext(), "/templates");
conf.setDefaultEncoding("UTF-8");
try {
Template tl = conf.getTemplate(fileName);
tl.process(this.setParams(), out);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
自定义标签tld文件(ftl.tld)
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>JSTL 1.1 core library</description>
<display-name>JSTL core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>ftl</short-name>
<uri>/ftl</uri>
<!-- 取ftl -->
<tag>
<description>取得ftl模板文件</description>
<name>getFtlTemplate</name>
<tag-class>com.test.freemarker.common.getFtlTemplateTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>fileName</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>parmsStr</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
在jsp上调用上面的自定义标签
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="ftl" uri="/WEB-INF/tld/ftl.tld" %>
<html>
<head>
<title></title>
</head>
<body>
<p>测试从模版中读取信息</p>
<ftl:getFtlTemplate fileName="header.ftl" parmsStr="{'user':'zhangsan','modifier':'lisi','pass':'123'}"/>
</body>
</html>