freemark

来源:互联网 发布:linux 查找字符串 编辑:程序博客网 时间:2024/05/16 03:28
public class HelloServlet extends HttpServlet {    private Configuration cfg;         public void init() {        // Prepare the FreeMarker configuration;        // - Load templates from the WEB-INF/templates directory of the Web app.        cfg = Configuration.getDefaultConfiguration();        cfg.setServletContextForTemplateLoading(                getServletContext(), "WEB-INF/templates");    }        protected void doGet(HttpServletRequest req, HttpServletResponse resp)        throws ServletException, IOException {                // Build the data-model        Map root = new HashMap();        root.put("message", "Hello World!");                // Get the templat object        Template t = cfg.getTemplate("test.ftl");                // Prepare the HTTP response:        // - Use the charset of template for the output        // - Use text/html MIME-type        FileWriter out = new FileWriter(new File("G:\\test.html"));        resp.setContentType("text/html; charset=" + t.getEncoding());                // Merge the data-model and the template        try {            t.process(root, out);            System.out.println(out);            out.flush();            System.out.println(out);        } catch (TemplateException e) {            throw new ServletException(                    "Error while processing FreeMarker template", e);        }    }}

<servlet>    <servlet-name>hello</servlet-name>    <servlet-class>example.HelloServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>hello</servlet-name>    <url-pattern>/hello</url-pattern>  </servlet-mapping>

0 0