JAVA-动态页面静态化(一)

xu.wang

发布于 2018.04.24 22:18 阅读 2429 评论 0

实现动态页面静态化 本文章使用freeMarker的方法将页面静态化。下面介绍下最基础的使用方式。

需要三个步骤。

第一步:引用freeMarker

maven直接添加下面的dependency即可。

    <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
    </dependency>

第二步: 创建一个测试类(我用一个controller进行设置)

 @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult test(HttpSession session)
    {
        JsonResult jsonResult = new JsonResult();

        String webappPath = session.getServletContext().getRealPath("/");

        // 配置对象, 配置模板位置
        Configuration configuration = new Configuration(
                Configuration.VERSION_2_3_22);
        try {
            configuration.setDirectoryForTemplateLoading(new File(
                    webappPath+"\\WEB-INF\\template"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取模板对象
        Template template = null;
        try {
            template = configuration.getTemplate("test.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 动态数据对象
        Map<String, Object> paramterMap = new HashMap<String, Object>();
        paramterMap.put("title", "hello world");
        paramterMap.put("msg", "这是一个Freemarker!");

        // 合并输出,new PrintWriter()中的参数为生成静态HTML的地址。
        try {
            template.process(paramterMap, new PrintWriter(webappPath+"\\assets\\test.html"));
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return jsonResult;
    }

第三步:创建模板

在WEB-INF文件夹中创建模板,

内容为:(取值方式和jstl很相似)

<html>
    <title>
        ${title} 
    </title>
    <body>
        ${msg}
    </body>
</html>

测试

运行controller即可生成HTML文件。如下