This is the description of my J2EE component
This is the display name of my J2EE component
HelloFreemarkerServlet
cn.com.freemark.servlet.test.HelloFreemarkerServlet
HelloFreemarkerServlet
/servlet/HelloFreemarkerServlet
即我们在浏览器访问“/servlet/HelloFreemarkerServlet”就会得到该Servlet类运行的结果。
package cn.com.freemark.servlet.test;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class HelloFreemarkerServlet extends HttpServlet {
private Configuration cfg;//freemarker的配置类
public void init() throws ServletException {
//在初始化Servlet的时候就做的事情:
cfg = new Configuration();//创建freemarker配置实例
//指定freemarker的上下文环境和模板路径:
cfg.setServletContextForTemplateLoading(
getServletContext(), "WEB-INF/template");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//装载map数据模型信息
Map root = new HashMap();
root.put("information", "欢迎光临!O(∩_∩)O哈哈~");
//设置具体模板名称,并生成模板对象
Template t = cfg.getTemplate("test.flt");
//设置响应输出类型和编码格式
//设置浏览器用utf8来解析返回的数据
response.setHeader("Content-type", "text/html;charset=UTF-8");
//设置servlet用UTF-8转码,而不是用默认的ISO8859
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();//创建相应内容写出对象
//将map数据模型与模板结合输出
try {
t.process(root, out);
} catch (TemplateException e) {
throw new ServletException("加载Freemarker模板失败!",e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
可以看到,在代码中,首先在init方法中初始化freemarker的配置类Configuration,指定上下文
FreeMarker 与 JavaWeb结合样例
${information}
大家参考即可,重点是以后要讲解的Freemarker与Web开发框架的结合。
转载请注明出处:http://blog.csdn.net/acmman/article/details/79248718