freeMarker生成静态页面

Posted 起个名字好难

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了freeMarker生成静态页面相关的知识,希望对你有一定的参考价值。

 

项目结构图

 

 

 footer.ftl

des==>${f.des}<br/>

<a href="http://www.baidu.com"> 百度 </a>

 

header.ftl

companyName==>${h.companyName}<br/>
address==>${h.address}<br/>

 

notice.ftl

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

  <body>
  <#include "header.ftl" parse=true encoding="utf-8">
  <hr/>

亲爱的${data.recipient}:

  您好!

  请查看如下通知:
  ${data.content}

  感谢您的阅读!

- ${data.publisher}
- ${data.dateTime}



  <hr/>
  <a href="#">用户列表</a><br/>
  <table border="1">
      <tr>
          <td>用户名</td>
          <td>年龄</td>
          <td>生日</td>
          <td>id</td>
          <td>操作</td>
      </tr>
      <#list users as user>
          <tr>
              <td>${user.name}</td>
              <td>${user.age}</td>
              <td>
              ${user.birthday?string("yyyy-MM-dd HH:mm:ss")}
              </td>
              <td>${user.id}</td>
              <td><a href="#">删除</a></td>
          </tr>
      </#list>
      
  </table>
<hr/>


<hr/>
  <#include "footer.ftl" parse=true encoding="utf-8">

</body>
</html>

 

 

Footer.java

package com.shm.entity;

public class Footer {

    private String des;

    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        this.des = des;
    }
    
    
}

 

Header.java

package com.shm.entity;
public class Header {

    private String companyName;
    
    private String address;

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
    
    
}

 

Notice.java

package com.shm.entity;

public class Notice {
    private String recipient;
    private String content;
    private String publisher;
    private String dateTime;
    public String getRecipient() {
        return recipient;
    }
    public void setRecipient(String recipient) {
        this.recipient = recipient;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getPublisher() {
        return publisher;
    }
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }
    public String getDateTime() {
        return dateTime;
    }
    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }
    
    
    
}

 

User.java

package com.shm.entity;

import java.util.Date;

public class User {
    
    private Integer id;

    private String name ;
    
    private int age;
    
    private Date birthday;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public User(Integer id,String name, int age, Date birthday) {
        super();
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.id = id;
    }

    public User() {
        super();
    }
    
    
}

 

DirectoryFilter.java

package com.shm.util;

import java.io.File;
import java.io.FilenameFilter;
public class DirectoryFilter implements FilenameFilter {

    String myString;
    public DirectoryFilter(String myString)
    {
        this.myString = myString;
    }
    
    public boolean accept(File dir,String name)
    {    //FilenameFilter.accept(File dir, String name) 
       // 测试指定文件是否应该包含在某一文件列表中。
        String f= new File(name).getName();
        if(f.contains(myString) || f.equals(myString)){
            return true;
        }
        return false;
    }

}

 

FreeMarkerUtil工具类
package com.shm.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.shm.entity.Footer;
import com.shm.entity.Header;
import com.shm.entity.Notice;
import com.shm.entity.User;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.Template;
import freemarker.template.Version;
import service.FooterService;
import service.HeaderService;
import service.UserService;

public class FreeMarkerUtil {
    
    public static final String CHARSET_UTF8 = "UTF-8";

    public static Version version = Configuration.VERSION_2_3_25; //FreeMarker版本号
    public static Configuration config;
    
    // 模板对象
    public static Template template;

    public static DefaultObjectWrapperBuilder defaultObjectWrapperBuilder;
    
    // 创建 Configuration 对象
    static {
        config = new Configuration(version);
        config.setDefaultEncoding(CHARSET_UTF8);// 设置默认编码 (至关重要 - 解决中文乱码问题)
        defaultObjectWrapperBuilder = new DefaultObjectWrapperBuilder(version); //用于创建defaultObjectWrapper
        config.setObjectWrapper(defaultObjectWrapperBuilder.build()); // 设置对象包装器
    }
    
    /**
     * 拼接内容数据
     * @param dataMap
     * @return
     */
    public static Map<String, Object> processBody(Map<String, Object> dataMap){
        Header h = HeaderService.getHeader();
        dataMap.put("h", h);
        Footer f = FooterService.gerFooter();
        dataMap.put("f", f);
        List<User> users = UserService.getUsers();
        dataMap.put("users", users);
        return dataMap;
    }
    
    /**
     * 根据template和dataMap生成文档内容
     * @param templatePath 模板路径
     * @param templateName 模板文件名称
     * @param templateName 生成的文件存放路径
     * @param templateName 生成的文件名称
     * @param templateName 是否强制覆盖已存在的文件
     * @param dataMap 需要填充的数据
     * @return 
     */
    public static String buildContent(final String templatePath, final String templateName, final String filePath, final String fileName, final boolean forceCovered, final Map<String, Object> dataMap) {
        Writer out = null;
        try    {
            //判断是否强制覆盖,如果是不覆盖则要检查该目录下是否已存在该文件
            if(!forceCovered){
                File path = new File(filePath);
                //判断是否已经存在该html文件
                String[] indexfileList = path.list(new DirectoryFilter(fileName));
                if(indexfileList == null || indexfileList.length == 0) {
                    
                } else {
                    return filePath + "目录下已存在" + indexfileList[0];
                }
            }
            
            // 设置要解析的模板所在的目录,并加载模板文件
            config.setDirectoryForTemplateLoading(new File(templatePath));
                        
            // 从模板目录下获取指定 ftl 模板文件
            Template template = config.getTemplate(templateName, CHARSET_UTF8);
            
            //生成引入的ftl中header与footer的数据
            processBody((Map<String, Object>) dataMap);
            
            /*// 字符串 字符输出流
            final StringWriter stringWriter = new StringWriter();
            final BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
             // 把 数据源写到模板中
            template.process(dataMap, bufferedWriter);
            
            // 刷新
            bufferedWriter.flush();
            // 关闭输出流
            bufferedWriter.close();
            
            // 获取输出的文本 (调用其 toString方法获得String)
            System.out.print(stringWriter.toString());*/
             
            // 合并数据模型与模板
            //html生成之后存放的路径
            out = new OutputStreamWriter(new FileOutputStream(filePath + "/" + fileName), CHARSET_UTF8);
            template.process(dataMap, out);
            
        } catch (Exception e) {
            e.printStackTrace();
            return "生成文件发生异常";
        } finally {
            if(out != null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "生成文件成功";
    }
    
    //测试
    public static void main(String[] args) {
        Notice notice = new Notice();
        notice.setRecipient("张三");
        notice.setPublisher("系统管理员");
        notice.setContent("这是通知内容,请记住。\\n不要问我是谁!");
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        notice.setDateTime(df.format(new Date()));
        
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("data", notice);
        
        String result = FreeMarkerUtil.buildContent("E:/templates", "notice.ftl", "E:/templates", "notice.html", false, dataMap);
        System.out.println(result);
    }
}

 

 

 

FooterService.java

package service;

import com.shm.entity.Footer;

public class FooterService {

    private static Footer f = new Footer();
    static{
        f.setDes("上海-哈哈!!!");
    }
    
    public static void update(String des){
        f.setDes(des);
    }
    
    public static Footer gerFooter(){
        return f;
    }
}

 

HeaderService.java

package service;

import com.shm.entity.Header;

public class HeaderService {

    private static Header h = new Header();
    
    static{
        h.setAddress("上海CBD");
        h.setCompanyName("上海!!!");
    }
    
    public static void update(String address,String companyName){
        h.setAddress(address);
        h.setCompanyName(companyName);
    }
    
    public static Header getHeader(){
        return h;
    }
}

 

UserService.java

package service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.shm.entity.User;

public class UserService {

    private static List<User> users = new ArrayList<User>();
    
    static{
        for(int i=0;i<10;i++){
            User u = new User(i,"ajun"+i,i+10,new Date());
            users.add(u);
        }
    }
    
    public static List<User> getUsers(){
        return users;
    }
    
    public static void delete(int index){
        for(int i=0 ;i<users.size();i++){
            User u = users.get(i);
            if(u.getId()==index){
                users.remove(u);
                //users.remove(index);
            }
        }
    }
}

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.shm</groupId>
  <artifactId>freeMarkerTest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>freeMarkerTest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
            <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.25-incubating</version>
        </dependency>

        
  </dependencies>
  <build>
    <finalName>freeMarkerTest</finalName>
  </build>
</project>

 

以上是关于freeMarker生成静态页面的主要内容,如果未能解决你的问题,请参考以下文章

页面缓存-freemarker静态处理

FreeMarker--04---页面静态化

freeMarker生成静态页面

生成freemarker静态页面的工具类

Freemarker 简介

java使用freemarker生成静态html页面