JSP学习笔记(三十一):使用freemarker生成静态页面
这篇文章的代码在上篇文章的基础之上,《JSP学习笔记(三十):freemarker入门例子》
把普通类Class1.java改为servlet类,Servlet1.java,并把原来的从输出到页面改为输出到文件。
package com.abc.test.action;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import freemarker.template.*;
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = -3598019779396031193L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Configuration cfg = new Configuration();
cfg.setServletContextForTemplateLoading(getServletContext(),
"WEB-INF/templates");
Map root = new HashMap();
root.put("name", "Tom");
Template t = cfg.getTemplate("test.ftl");
File file = new File(getServletContext().getRealPath("/")
+ "\\test.htm");
if (!file.exists())
file.createNewFile();
Writer out = new FileWriter(file);
try {
t.process(root, out);
} catch (TemplateException e) {
}
}
}
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import freemarker.template.*;
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = -3598019779396031193L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Configuration cfg = new Configuration();
cfg.setServletContextForTemplateLoading(getServletContext(),
"WEB-INF/templates");
Map root = new HashMap();
root.put("name", "Tom");
Template t = cfg.getTemplate("test.ftl");
File file = new File(getServletContext().getRealPath("/")
+ "\\test.htm");
if (!file.exists())
file.createNewFile();
Writer out = new FileWriter(file);
try {
t.process(root, out);
} catch (TemplateException e) {
}
}
}
并把servlet映射添加到web.xml文件中,方法见《JSP学习笔记(二十三):我的第一个servlet页面》