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 {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		Configuration 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 block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+"/html/form.html";
		resp.sendRedirect(url);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(req, resp);
	}

	@Override
	public void init() throws ServletException {
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值