freemarker 页面静态化

简介:           Insert title here user info: ${user.userName }     ...

 

 

 

 

 

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<#if  users?size != 0> 
<div class=”user”> 
     <strong>user info:</strong> 
     <#list users as user> 
    <p> ${user.userName } </p>
  </#list> 
</div> 
<#else> 
<div class=”user”></div> 
</#if> 


</body>
</html>

 

 

<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<bean id="freemakerCongfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath">
			<value>/WEB-INF/ftl/</value>
		</property>
		<property name="freemarkerSettings">
			<props>
				<prop key="defaultEncoding">UTF-8</prop>
			</props>
		</property>
	</bean>

</beans>

 

 

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.curiousby.entity.User;
import com.curiousby.util.FreeMarkerOnParamLinsenter;
import com.curiousby.FreeMarkerRequest;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;

/**
 * @Type StaticPageController.java
 * @Desc 
 * @author baoyou curiousby@163.com
 * @date 2017年3月19日 下午8:00:49
 * @version 
 */
@Controller
@RequestMapping(value = "/test/staticpage")
public class StaticPageController {

    @Autowired
    FreeMarkerConfigurer freemakerCongfig;

    @RequestMapping(value = "/")
    public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {

        new FreeMarkerRequest(new FreeMarkerOnParamLinsenter() {

            @Override
            public void onParamLinsenLinsenter(Map<String, Object> params) {
                User user = new User();
                user.setUserName("baoyou");
                List<User> users = new ArrayList<>();
                users.add(user);
                params.put("users", users);
            }
        }).request(request, response, freemakerCongfig, null, "freemaker.ftl", "index.html");
    }

    @RequestMapping(value = "/home")
    public void home(HttpServletRequest request, HttpServletResponse response) throws Exception {

        new FreeMarkerRequest(new FreeMarkerOnParamLinsenter() {

            @Override
            public void onParamLinsenLinsenter(Map<String, Object> params) {
                User user = new User();
                user.setUserName("baoyou");
                List<User> users = new ArrayList<>();
                users.add(user);
                params.put("users", users);
            }
        }).request(request, response, freemakerCongfig, "home", "index.ftl", "index.html");
    }
}
/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年3月19日 baoyou curiousby@163.com creat
 */

 

 

/*
 * This software is the confidential and proprietary information of
 * curiousby Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.curiousby.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer; 
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @Type FreeMarkerUtil.java
 * @Desc 
 * @author baoyou curiousby@163.com
 * @date 2017年3月20日 下午12:18:23
 * @version 
 */
public class FreeMarkerUtil {

    /**
     * 
     * @param freeMarkerConfig
     * @param templateName
     * @param request
     * @param map
     * @param filePath
     * @param fileName
     */
    public static void createHtml(FreeMarkerConfig freeMarkerConfig, 
                                  String templateName,
                                  HttpServletRequest request, 
                                  Map<?, ?> map, 
                                  String filePath,
                                  String fileName) {
        Writer out = null;
        try {
            Template template = freeMarkerConfig.getConfiguration().getTemplate(templateName);
            String htmlPath = request.getSession().getServletContext().getRealPath("/")+  ((filePath == null || "".equals(filePath)) ? "" : filePath + "/") + "/"+ fileName;
            File htmlFile = new File(htmlPath);
            if (!htmlFile.getParentFile().exists()) {
                htmlFile.getParentFile().mkdirs();
            }
            if (!htmlFile.exists()) {
                htmlFile.createNewFile();
            }
            out = new OutputStreamWriter(new FileOutputStream(htmlPath), "UTF-8");
            template.process(map, out);
            out.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                out = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param request
     * @param filePath
     * @param fileName
     * @return
     */
    public static boolean exits(HttpServletRequest request, 
                                                       String filePath,
                                                       String fileName) {
        boolean flag = false; 
        String htmlPath = request.getSession().getServletContext().getRealPath("/") +  ((filePath == null || "".equals(filePath)) ? "" : filePath + "/") + "/"+ fileName;
        File htmlFile = new File(htmlPath);
        if (htmlFile.exists()) {
            flag = true;      
        }
        return flag;
    }

}


 

/*
 * This software is the confidential and proprietary information of
 * curiousby Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.curiousby.util;

import java.util.Map;

/**
 * @Type FreeMarkerOnParamLinsenter.java
 * @Desc 
 * @author baoyou curiousby@163.com
 * @date 2017年3月20日 下午12:27:09
 * @version 
 */
public interface FreeMarkerOnParamLinsenter {

    public void onParamLinsenLinsenter(Map<String,Object> params);
}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年3月20日 baoyou curiousby@163.com creat
 */

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @Type FreeMarkerRequest.java
 * @Desc 
 * @author baoyou curiousby@163.com
 * @date 2017年3月20日 下午12:26:31
 * @version 
 */
public class FreeMarkerRequest {

    private FreeMarkerOnParamLinsenter onParamLinsenter;

    public FreeMarkerRequest(FreeMarkerOnParamLinsenter onParamLinsenter) {
        this.onParamLinsenter = onParamLinsenter;
    }

    public void request(HttpServletRequest request, HttpServletResponse response,
                        FreeMarkerConfigurer freemakerCongfig, String filePath,String ftlName, String fileName)
             {

        Map<String, Object> params = new LinkedHashMap<String, Object>();
        this.onParamLinsenter.onParamLinsenLinsenter(params);
        boolean exits = FreeMarkerUtil.exits(request, filePath, fileName);
        Writer out = null;
        try {
            if (!exits) {
                File path = new File(request.getServletContext().getRealPath("/staticpage") + "/" +  ((filePath == null || "".equals(filePath)) ? "" : filePath + "/") );
                if(!path.exists()){
                    path.mkdirs();
                }
                Template temple = freemakerCongfig.getConfiguration().getTemplate( ((filePath == null || "".equals(filePath)) ? "" : filePath + "/") + ftlName);
                out = new OutputStreamWriter(new FileOutputStream(
                        request.getServletContext().getRealPath("/staticpage") + "/" +  ((filePath == null || "".equals(filePath)) ? "" : filePath + "/") + fileName));
                temple.process(params, out);//处理

            }

            response.sendRedirect(request.getServletContext().getContextPath() + "/staticpage/" + ((filePath == null || "".equals(filePath)) ? "" : filePath + "/") + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) { 
            e.printStackTrace();
        } finally {
            if (out!=null) {
                try {
                    out.close();
                } catch (IOException e) { 
                    e.printStackTrace();
                }
            }
        }
    }

}

/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年3月20日 baoyou curiousby@163.com creat
 */

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和微信捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

 

  

目录
相关文章
|
4月前
|
Python
配置模板引擎
【8月更文挑战第6天】配置模板引擎。
44 7
|
7月前
|
前端开发 JavaScript
thymeleaf局部刷新
thymeleaf局部刷新
109 0
|
XML Java 程序员
模板引擎:第一章:FreeMarker
模板引擎:第一章:FreeMarker
199 0
模板引擎:第一章:FreeMarker
|
XML 缓存 Java
页面静态化技术---Freemarker介绍
页面静态化技术---Freemarker介绍
页面静态化技术---Freemarker介绍
|
Java 程序员 Apache
模板引擎——FreeMarker初体验
FreeMarker 是一款模板引擎:一种基于模板的、用来生成输出文本(任何来自于 HTML格式的文本用来自动生成源代码)的通用工具。
|
XML Java 应用服务中间件
Thymeleaf一篇就够了
今天我们来学习Thymeleaf,如果你对Thymeleaf比较陌生也不要紧,它很容易学习与理解,并有着自己鲜明的特色
290 0
Thymeleaf一篇就够了
|
设计模式 前端开发 Java
【JavaWeb】模板引擎Thymeleaf
内容提取出来单独的放在一个文件中,称为模板,对于一些动态的内容,可以将这些内容在模板中使用占位符占位,当服务器把这些动态的内容计算好了之后,就可以把模板中占位符替换成动态计算的结果,然后把组装好的HTML格式的字符串在返回给浏览器
【JavaWeb】模板引擎Thymeleaf
|
消息中间件 前端开发 应用服务中间件
淘淘商城中freemarker静态化方案
淘淘商城中freemarker静态化方案
淘淘商城中freemarker静态化方案
|
存储 缓存 前端开发
网站页面静态化(二)thymeleaf生成
本文说明了如何基于springboot和thymeleaf的全站页面静态化方案的大概解决方案​雏形。例子中说明了具体的处理流程以及关键技术,至于存储和网页模板需要根据实际项目进行​调整开发。
480 0
网站页面静态化(二)thymeleaf生成
|
Java Spring
常见的模版引擎
常见的模版引擎
79 0