freemarker 页面静态化

 

 

 

<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 [email protected]
 * @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 [email protected] creat
 */
扫描二维码关注公众号,回复: 495501 查看本文章
/*
 * 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 [email protected]
 * @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 [email protected]
 * @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 [email protected] 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 [email protected]
 * @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 [email protected] creat
 */

捐助开发者

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



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

  

猜你喜欢

转载自knight-black-bob.iteye.com/blog/2364179