1.首先从官方下载freemarker的包,下载地址:http://freemarker.sourceforge.net/freemarkerdownload.html
2.把包lib/freemarker.jar拷贝到项目中
3.新建模板文件WEB-INF/templates/test.ftl,内容如下:
Hello,${name}
!
4.新建一个操作类Class1.java,内容如下:
package
com.abc.web;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.jsp.PageContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class Class1 {
public void execute(PageContext pageContext) throws Exception
{
Configuration cfg = new Configuration();
cfg.setServletContextForTemplateLoading(pageContext.getServletContext(), " WEB-INF/templates " );
Map root = new HashMap();
root.put( " name " , " Tom " );
Template t = cfg.getTemplate( " test.ftl " );
Writer out = pageContext.getResponse().getWriter();
t.process(root, out);
}
}
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.jsp.PageContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class Class1 {
public void execute(PageContext pageContext) throws Exception
{
Configuration cfg = new Configuration();
cfg.setServletContextForTemplateLoading(pageContext.getServletContext(), " WEB-INF/templates " );
Map root = new HashMap();
root.put( " name " , " Tom " );
Template t = cfg.getTemplate( " test.ftl " );
Writer out = pageContext.getResponse().getWriter();
t.process(root, out);
}
}
5.新建一个jsp页面test1.jsp,内容如下:
<%
@ page language
=
"
java
"
contentType
=
"
text/html; charset=GB2312
"
pageEncoding = " GB2312 " %>
<% @ page import = " com.abc.web.Class1 " %>
<! DOCTYPE html PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " " http://www.w3.org/TR/html4/loose.dtd " >
< html >
< head >
< meta http - equiv = " Content-Type " content = " text/html; charset=GB2312 " >
< title > Insert title here </ title >
</ head >
< body >
<%
Class1 c1 = new Class1();
c1.execute(pageContext);
%>
</ body >
</ html >
pageEncoding = " GB2312 " %>
<% @ page import = " com.abc.web.Class1 " %>
<! DOCTYPE html PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " " http://www.w3.org/TR/html4/loose.dtd " >
< html >
< head >
< meta http - equiv = " Content-Type " content = " text/html; charset=GB2312 " >
< title > Insert title here </ title >
</ head >
< body >
<%
Class1 c1 = new Class1();
c1.execute(pageContext);
%>
</ body >
</ html >
页面的显示效果为:
Hello,Tom!
这里有一份非常详细的freemarker的技术文档:http://www.sunjava.cn/FreeMarker.htm