public static void main(String[] args) throws Exception { /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File("/Users/ian.goldsmith/projects/freemarker")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); /* * You usually do these for MULTIPLE TIMES in the application * life-cycle: */ /* Create a data-model */ Map message = new HashMap(); message.put( "contentAsXml", freemarker.ext.dom.NodeModel.parse( new File("/Users/ian.goldsmith/projects/freemarker/test.xml"))); Map root = new HashMap(); root.put("message", message); /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate("testxml.ftl"); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); // Note: Depending on what `out` is, you may need to call `out.close()`. // This is usually the case for file output, but not for servlet output. }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map root = new HashMap(); Connection conn = null; conn = ConFact.getInstance().makeConnection(); String id = req.getParameter("id"); String sql = "select title,description,language_id from film where film_id=" + id + ";"; java.sql.PreparedStatement pst; try { pst = conn.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while (rs.next()) { java.sql.PreparedStatement pst1; String sql1 = "select name from language where language_id=" + rs.getString(3) + ";"; pst1 = conn.prepareStatement(sql1); ResultSet rs1 = pst1.executeQuery(); while (rs1.next()) { Template t = cfg.getTemplate("test.ftl"); root.put("title", rs.getString(1)); root.put("description", rs.getString(2)); root.put("language", rs1.getString(1)); resp.setContentType("text/html; charset=" + t.getEncoding()); Writer out = resp.getWriter(); t.process(root, out); } rs1.close(); } rs.close(); pst.close(); conn.close(); } catch (TemplateException e) { e.printStackTrace(); } catch (SQLException e1) { e1.printStackTrace(); } }