freemarker基于web的入门例子
import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Locale;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 GenerateHtml extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubConfiguration cfg = new Configuration();cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");cfg.setEncoding(Locale.getDefault(), "UTF-8");try {Map root = new HashMap();List<User> users = new ArrayList<User>();User u1 = new User();u1.setId("123");u1.setName("王五");users.add(u1);User u2 = new User();u2.setId("2345");u2.setName("张三");User u3 = new User();u3.setId("fgh");u3.setName("王八");users.add(u2);users.add(u3);root.put("userList", users);Map product = new HashMap();root.put("lastProduct", product);product.put("url", "http://www.google.com");product.put("name", "green hose");Template template = cfg.getTemplate("test.ftl", "UTF-8");template.setEncoding("UTF-8");String htmlPath = this.getServletContext().getRealPath("/html")+"/"+"form.html";File htmlFile = new File(htmlPath);if(!htmlFile.exists()){//System.out.println("file exist");htmlFile.createNewFile();}Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"UTF-8"));template.process(root, out);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (TemplateException e) {// TODO Auto-generated catch blocke.printStackTrace();}String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+"/html/form.html";resp.sendRedirect(url);}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubthis.doPost(req, resp);}@Overridepublic void init() throws ServletException {}}?