Velocity generates static HTML based on the template

Source: Internet
Author: User
Tags save file

A CMS project for the new company is to be used, which is recorded here

I. Project Document Map

Second, springmvc-servlet.xml add
<!--define environment variable files--    <bean id= "Propertyholder" class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">        <property name=" Systempropertiesmodename "value=" System_properties_mode_override "/>        <property name=" Ignoreresourcenotfound "value=" true "/>        <property name=" Locations ">            <list>                <value >classpath*:/*.properties</value>            </list>        </property>    </bean>
Third, HTML_TEMPLATE.VM
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">Four, the controller 
Package Com.geenk.web.controller.generatehtml;import Com.geenk.web.velocity_engine. Generatehtmlutil;import Org.springframework.beans.factory.annotation.value;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.responsebody;import Java.util.hashmap;import java.util.Map;/** * @author Duchong * @since 2018-04-28 18:51 **/@Controllerpublic class Generatecontroller {@Value ("${filepath}") Private Stri    Ng FilePath;    @Value ("${templatepath}") Private String TemplatePath; @ResponseBody @RequestMapping (value = "/html", method = requestmethod.get) public String generatehtml () {//general this            In the database is a list of records detected, and then traverse the list, generate HTML, and store the path, usually take "config + table field value", as the storage path//here with for (int i=1;i<10;i++) {            Page to show the data map<string,object> map=new hashmap<> (); Map.put ("title", "NewS "+i);            Map.put ("UserId", I);            Map.put ("UserName", "Test" +i);            Map.put ("mobile", "18106519020");            Map.put ("Email", "[email protected]");        Generatehtmlutil.generatehtmlbyvelocity ("News" +i,filepath,templatepath,map, "list");    } return "Over"; }}

Five, Tool class

Package Com.geenk.web.velocity_engine;import Org.apache.velocity.template;import Org.apache.velocity.velocitycontext;import Org.apache.velocity.app.velocity;import Org.slf4j.Logger;import Org.slf4j.loggerfactory;import Java.io.bufferedwriter;import Java.io.file;import Java.io.FileOutputStream;import Java.io.outputstreamwriter;import java.util.properties;/** * @author duchong * @since 2018-04-28 18:35 **/public class Ge    neratehtmlutil {static Logger Logger = Loggerfactory.getlogger (Generatehtmlutil.class);  /** * Generate a static HTML file from the velocity template * The file name of the file generated by filename * @param * @param filePath Save File location * @param templatepath Velocity template File path * @param params collection * @param variables that need to be conveniently or used on the PageName page, can be any value */public static void Generateh Tmlbyvelocity (String fileName, String FilePath, String templatepath, Object params, S        Tring pageName) {String finalfilepath=filepath+ file.separator+filename+ ". html"; try {//Set loadTemplate file, look for properties P = new properties () under Classpath; P.put ("File.resource.loader.class", "Org.apache.velocity.runtime.resource.loader.ClasspathResourceLoade            R ");            Velocity.init (P);            FileOutputStream fos = new FileOutputStream (Finalfilepath);            BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (FOS, "UTF8"));            Template velocity_template = velocity.gettemplate (TemplatePath, "UTF8");            Velocitycontext context = new Velocitycontext ();            Context.put (pageName, params);            Velocity_template.merge (Context,writer);        Writer.close (); } catch (Exception e) {logger.error ("File path failed!        ", e); }    }}
Vi.. Operation

Browser input localhost:8866/html, display over

Velocity generates static HTML based on the template

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.