`
knight_black_bob
  • 浏览: 842122 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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 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
 */

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

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



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

 

  

  • 大小: 49.8 KB
  • 大小: 151.6 KB
分享到:
评论

相关推荐

    java Freemarker页面静态化实例详解

    总结起来,Java中的Freemarker页面静态化实例详解主要涉及Freemarker的基本用法、数据格式化以及处理空值的策略。通过对这些知识点的掌握,开发者可以有效地利用Freemarker进行静态页面生成,从而提高网站的响应速度...

    httpclient,freemarker的静态化分页

    总的来说,`httpclient`与`freemarker`在页面静态化分页中的结合使用,既保证了数据的动态获取,又实现了静态文件的高效生成,是Web开发中一种实用的优化手段。通过合理的代码组织和设计,可以构建出高效且易于维护...

    freemark 页面静态化

    总的来说,Freemarker页面静态化能够提高Web应用的性能,减少服务器负载,提升用户体验,尤其适合新闻资讯、博客等需要大量静态页面的网站。同时,它也有助于SEO优化,因为搜索引擎更容易抓取静态HTML页面。因此,...

    Freemarker网站静态化的实现实例源码(eclipse)

    本实例源码是关于如何利用Freemarker进行网站静态化的具体实践,主要涉及到以下几个核心知识点: 1. **Freemarker模板语言**:Freemarker使用简单的文本模板语言,将数据模型与HTML模板结合,生成最终的HTML页面。...

    SpringBoot2 整合FreeMarker模板,完成页面静态化处理.docx

    【SpringBoot2 整合FreeMarker模板,完成页面静态化处理】 在Web开发中,页面静态化是一种提高网站性能和用户体验的技术。它涉及到将原本动态生成的页面转换为静态HTML文件,减少对服务器的依赖,加快页面加载速度...

    struts1.2+freemarker实现登录成功页面静态化例子

    总结来说,这个例子展示了如何结合Struts1.2和Freemarker2.3.8实现登录成功页面的静态化,通过静态化可以提高网站性能,减轻服务器负担,提升用户体验。在实际开发中,开发者可以根据项目需求灵活运用这些技术和策略...

    Jsp页面静态化(freemarker)教程及源码

    前台页面的静态化就有利于SEO,所以这个问题摆在了我的面前,在网上一搜,关于这方面的资料不是很多,又很杂,关于这方面的知识,越来或多的程序员将会碰到,原来项目中这部分静态化的功能主要由我来做的,现在我将...

    freemarker把jsp静态化简单应用

    本教程将介绍如何在Java Web项目中利用FreeMarker进行JSP页面的静态化,适合初学者入门学习。 1. **FreeMarker基本概念** FreeMarker是一个基于模板的语言,它与编程语言不同,不包含任何控制结构或函数调用。它的...

    有关Java页面静态化

    Java页面静态化主要有两种方式:服务器端静态化和客户端静态化。 1. 服务器端静态化: - **预渲染(Prerendering)**:在用户请求之前,系统自动将一些常用或者热点页面生成静态HTML文件,存储在文件系统或CDN上。...

    java JSP页面静态化总结_动态页面变为静态页面以减少访问数据库的次数提高速度.zip

    1. **JSP页面静态化原理**: - JSP页面静态化的核心思想是将原本需要服务器实时解析的动态内容,提前转换为静态HTML文件,存储在服务器上。这样,当用户请求这些页面时,服务器不再需要执行JSP脚本,而是直接返回...

    java 页面静态化

    在进行页面静态化时,我们还需要考虑一些问题,比如如何处理动态内容(如用户登录状态、个性化推荐)、如何同步静态文件和动态数据、以及如何清理过期的静态文件等。这些问题可以通过设计合理的缓存策略和定时任务来...

    ssh+FreeMarker静态化网页例子

    ssh+FreeMarker静态化网页例子

    教你如何用FreeMarker生成静态页面.doc

    本篇文章将详细讲解如何利用FreeMarker来生成静态页面。 首先,我们需要理解FreeMarker的基本工作原理。在FreeMarker模板文件中,我们可以编写HTML结构,同时嵌入特定的FreeMarker语法,如`&lt;#if&gt;`、`&lt;#foreach&gt;`等...

    struts2+freemarker 生成静态页面

    4. **实现过程**:在Struts2中,可以通过自定义Result类型来实现静态化。这个Result类型会在Action处理完请求后,将生成的FreeMarker模板内容写入到一个静态HTML文件中。同时,需要设置适当的缓存策略,例如根据内容...

    Struts2整合Freemarker生成静态页面

    这通常通过在Action中触发静态化逻辑,将Freemarker渲染后的HTML保存到磁盘,然后直接返回这些静态页面。 9. **错误和异常处理**:Struts2和Freemarker都有自己的错误处理机制。当模板或Action执行出错时,可以通过...

    动态页面静态化汇总--页面静态化方案

    在动态页面静态化中,Freemarker可以用来生成静态HTML文件,模板中填入数据模型后,静态页面即可自动生成。 3. **URLRewrite**: URLRewrite是一个常用的Apache服务器模块,它可以实现URL重写功能。在静态化过程中...

    页面静态化

    页面静态化是Web开发中的一个重要概念,主要目的是提高网站的访问速度和搜索引擎优化(SEO)。在Java Web开发中,页面静态化通常涉及到将动态生成的HTML页面转化为纯HTML文件,以便用户请求时无需通过服务器执行复杂...

    springboot整合FreeMarker模板,完成页面静态化处理

    、页面静态化 1、动静态页面 静态页面 即静态网页,指已经装载好内容HTML页面,无需经过请求服务器数据和编译过程,直接加载到客户浏览器上显示出来。通俗的说就是生成独立的HTML页面,且不与服务器进行数据交互。 ...

Global site tag (gtag.js) - Google Analytics