Servlet中施用freeMarker

Servlet中使用freeMarker

第一步:导入freemarker jar

第二步:在WEB-INF\templates文件夹下编写test.ftl模板

<html>

<head>

  <title>FreeMarker Example Web Application 1</title>

</head>

<body>

  <h1>${message}</h1>

</body>

</html>

第三步:编写servlet

package com.test.freemarker;

 

import java.util.*;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import freemarker.template.*;

 

publicclass HelloServlet extends HttpServlet {

    private Configuration cfg;

 

    publicvoid init() {

       cfg = new Configuration();

       cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");

    }

 

    protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,

           IOException {

       Map root = new HashMap();

       root.put("message", "Hello World!");

 

       Template t = cfg.getTemplate("test.ftl");

 

       resp.setContentType("text/html; charset=" + t.getEncoding());

       Writer out = resp.getWriter();

       try {

           t.process(root, out);

       } catch (TemplateException e) {

           thrownew ServletException("Error while processing FreeMarker template", e);

       }

    }

}

第四步:配置web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"

    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>freeMarkerServlet</display-name>

    <servlet>

       <servlet-name>hello</servlet-name>

        <servlet-class>com.test.freemarker.HelloServlet</servlet-class>

    </servlet>

    <servlet-mapping>

       <servlet-name>hello</servlet-name>

       <url-pattern>/hello</url-pattern>

    </servlet-mapping>

</web-app>