A simple example of a Web project using Freemarker __web

Source: Internet
Author: User
Freemarker is a template engine, a generic tool for generating static files based on templates, and is a development package for Java programmers. The following describes how Web applications can use Freemarker to generate static HTML.

Before the operation, the Freemarker jar package is introduced and the Freemarker jar package is placed under Webcontent/web-inf/lib 1. First, create a new package in the WEB Project COM.TEST.FTL to store the template file. Create a new template file Hello.ftl and fill in the following

 
2. Writing Freemarker Tool class 
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 = 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");

            Set to where to read the corresponding FTL template file Cfg.setclassfortemplateloading (This.getclass (), "/COM/TEST/FTL");

            Locate the file named name in the template file directory Template temp = cfg.gettemplate (name);
        return temp;
            }catch (Exception e) {e.printstacktrace ();
        return null;
}

    }


        /* Console output */public void print (String name,map<string,object> root) {try {
                The template file can be exported to the corresponding stream Template temp = this.getemplate (name) through Template;

            Temp.process (Root, new PrintWriter (System.out));
            }catch (Exception e) {e.printstacktrace (); }/* Output HTML file */public void Fprint (String name,map<string,object> root,list&lt ;

            String> list) {FileWriter out = null;
                try {//through a file output stream, you can write to the appropriate file, where you use the absolute path 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 titl
            e) {//FileWriter out = null;
            Writer Writer = null;
                try {//through a file output stream, you can write to the appropriate file, where you use the absolute path 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); Templatetemp = getemplate (name);

            Temp.process (root, writer);
            }catch (Exception e) {e.printstacktrace ();
                    }finally {try {if (writer!= null) {writer.close ();
                }}catch (Exception e) {e.printstacktrace ();
 }
            }

        }
}
3. Write a Web controller, which is described in detail in the code.
@Controller public class TestController1 {@RequestMapping ("/test") public void test (Blog blog,httpservletrequest
          Request,httpservletresponse response) {Configuration cfg=new Configuration ();
          Gets the template path String templatepath=this.getclass (). getClassLoader (). GetResource ("/COM/TEST/FTL"). GetPath ();
            try {//configuration template path Cfg.setdirectoryfortemplateloading (new File (TemplatePath));
            Cfg.setdefaultencoding ("UTF-8");
            Gets the target template Template Template = cfg.gettemplate ("HELLO.FTL"); Create the destination HTML file file=new files (Request.getservletcontext (). Getrealpath ("/public/" +blog.getblogtitle_ch () + ". HT
            ML "));
             Creates a character output stream Writer writer=new outputstreamwriter (new FileOutputStream (file), "UTF-8");
             The map is used to pass data to the template, writer the template content to the newly created HTML file template.process (map, writer);
             Writer.flush ();
        Writer.close (); catch (IOException | Templateexception E1) {//TODO auto-generated catch block E1.printstacktrace (); } 
    }
}
4. Create entity classes for submitting information.
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;
    The 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. Front-end Submission request
<! DOCTYPE html>
This completes a simple example of a Web project using Freemarker to generate static pages.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.