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 {
}
}