web项目使用freemarker的简单例子

Freemarker 是一款模板引擎,是一种基于模版生成静态文件的通用工具,它是为java程序员提供的一个开发包。以下介绍web应用如何使用freemarker生成静态html。

操作前先引入freemarker的jar包,将freemarker的jar包放到WebContent/WEB-INF/lib 下

1.首先在web工程中新建一个包 com.test.ftl 用来存放模板文件,再新建一个模板文件 hello.ftl,填入如下内容

这里写图片描述

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
${blog.blogType}
<br>
${blog.blogTitle_ch}
<br>
${blog.article}
</div>
</body>
</html>
2. 编写freemarker工具类
package com.test.freemaker;
import java.io.File;
import java.io.FileOutputStream;
import com.google.common.base.Joiner;
import com.test.entity.Blog;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Calendar;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreemakerUtil {
    private   Date date = new Date();
    private    Calendar calendar = Calendar.getInstance();
    public static String template="hello.ftl";
    public    Date getDate() {
    return date;
    }

    private   Calendar getCalendar() {  
        return  calendar;
    }

    private    String getTimeUrl() {
        SimpleDateFormat s=new SimpleDateFormat("yyyy/MM/dd/");
        String curDate = s.format(getCalendar().getTime());
//      int year = getCalendar().get(Calendar.YEAR);
//      int month =getCalendar().get(Calendar.MONTH)+1;
//      int day = getCalendar().get(Calendar.DAY_OF_MONTH);
//      int hour = getCalendar().get(Calendar.HOUR_OF_DAY);
        return curDate;
//      return ""+year+"/"+month+"/"+day+"/";
//      return ""+year+"-"+month+"-"+day+" "+hour+":00";
    }

    public   Template geTemplate(String name) {

        try {
            Configuration cfg = new Configuration();
            String templatePath  = this.getClass().getClassLoader().getResource("/com/test/ftl").getPath();
            cfg.setDefaultEncoding("UTF-8");

            // 设定去哪里读取相应的ftl模板文件
            cfg.setClassForTemplateLoading(this.getClass(), "/com/test/ftl");

            // 在模板文件目录中找到名称为name的文件
            Template temp = cfg.getTemplate(name);

            return temp;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }

    }



        /*控制台输出*/
        public void print(String name,Map<String,Object> root) {
            try {
                 // 通过Template可以将模板文件输出到相应的流
                Template temp = this.geTemplate(name);
                temp.process(root, new PrintWriter(System.out));

            }catch(Exception e) {
                e.printStackTrace();
            }       
        }

        /*  输出html文件*/
        public   void fprint(String name ,Map<String,Object> root,List<String> list) {
            FileWriter out = null;

            try {
                 // 通过一个文件输出流,就可以写到相应的文件中,此处用的是绝对路径
                String url =getTimeUrl();
                File file = new File("/public/"+url+list.get(0)+"/index.html");
                if(!file.exists()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                out = new FileWriter(file);
                Template temp = geTemplate(name);
                temp.process(root, out);

            }catch(Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if(out != null) {
                        out.close();
                    }
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }

        }

        public   void fprint(String name,String path,Map<String,Object> root,String title) {
//          FileWriter out = null;
            Writer  writer = null;
            try {
                 // 通过一个文件输出流,就可以写到相应的文件中,此处用的是绝对路径
                String url =getTimeUrl();
                File file = new File(path+url+title+"/index.html");
                if(!file.exists()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();

                }
                writer=new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
//              out = new FileWriter(file);
                Template temp = geTemplate(name);
                temp.process(root, writer);

            }catch(Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if(writer != null) {
                        writer.close();
                    }
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }

        }
}
3. 编写web控制器,代码中已给出详尽的说明。
@Controller
public class TestController1 {
    @RequestMapping("/test")
    public void test(Blog blog,HttpServletRequest request,HttpServletResponse response) {   
          Configuration cfg=new Configuration();
          //获取模板路径
          String templatePath=this.getClass().getClassLoader().getResource("/com/test/ftl").getPath();
          try {   
//配置模板路径            cfg.setDirectoryForTemplateLoading(new File(templatePath));
            cfg.setDefaultEncoding("UTF-8");
            //获取目标模板
            Template template = cfg.getTemplate("hello.ftl");
            //创建目标html文件
            File file=new File(request.getServletContext().getRealPath("/public/"+blog.getBlogTitle_ch()+".html"));
            //创建字符输出流
             Writer writer=new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
             //map用来给模板传递数据,writer将模板内容写入到上面新建的html文件
             template.process(map, writer);
             writer.flush();
             writer.close();
        } catch (IOException | TemplateException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } 
    }
}
4.创建实体类,用来存放提交信息。
import java.io.Serializable;
@SuppressWarnings("serial")
public class Blog  implements Serializable {
    private int blogId;
    private String blogTime;
    private String article;
    private String blogType;
    private String blogTitle_ch;
    private String blogTitle_en;
    private String time;
    public String getBlogTitle_ch() {
        return blogTitle_ch;
    }
    public void setBlogTitle_ch(String blogTitle_ch) {
        this.blogTitle_ch = blogTitle_ch;
    }
    public String getBlogTitle_en() {
        return blogTitle_en;
    }
    public void setBlogTitle_en(String blogTitle_en) {
        this.blogTitle_en = blogTitle_en;
    }
    public int getBlogId() {
        return blogId;
    }
    public void setBlogId(int blogId) {
        this.blogId = blogId;
    }
    public String getBlogTime() {
        return blogTime;
    }
    public void setBlogTime(String blogTime) {
        this.blogTime = blogTime;
    }
    public String getArticle() {
        return article;
    }
    public void setArticle(String article) {
        this.article = article;
    }
    public String getBlogType() {
        return blogType;
    }
    public void setBlogType(String blogType) {
        this.blogType = blogType;
    }
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }   


}
5.前端提交请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    <form id="form1" action="test" method="post">   
         类型:<input type="text" name="blogType"><br>
         题目:<input type="text" name="blogTitle_ch"><br>
         内容:<textarea name="article"></textarea><br>
         <input type="submit" value="提交">
    </form>
</body>
</html>
这样,就完成了web项目使用freemarker生成静态页面的一个简单例子。

猜你喜欢

转载自blog.csdn.net/qq_23483671/article/details/79018892