一,在项目中编写***.ftl文件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>测试</title>
    </head>
    <body>
        ${date?string("yyyy")}
    </body>
</html>

二,在servlet中使用freemarker

@WebServlet(name="test",urlPatterns="/test")
public class servlet_test extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Configuration cfg;
    @Override
    public void init() throws ServletException {
        //initialize operation
        cfg=new Configuration(Configuration.VERSION_2_3_25);
        cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/ftl");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        Map data=new HashMap();
        data.put("date", new Date());
        //得到模板
        try {
            //将模板和数据结合,并返回浏览器
            Template template=cfg.getTemplate("1test.ftl");
            template.process(data, response.getWriter());
        } catch (Exception e) {
            //e.printStackTrace();
            response.getWriter().print("暂时无数据");
        }
    }
}

 

 posted on 2017-02-21 17:37  夏末秋萍  阅读(547)  评论(0编辑  收藏  举报