Velocity generates static html based on templates

  A CMS project of the new company will use it, record it here

1. Project file diagram

Second, springmvc-servlet.xml add

<!-- Define the environment variable file-->
    <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>

三、html_template.vm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>${list.title}</title>
    </head>
    <body>
        <h2>${list.title}</h2>
        <table border="1" style="margin-left: 100px" >
            <tr>
                <th class="jobs-time">序号</th>
                <th class="jobs-title">名称</th>
                <th class="jobs-title">mobileNo</th>
                <th class="jobs-title">email</th>
            </tr>
            #if($!list)
                <tr>
                    <td>${list.userId}</td>
                    <td>${list.userName}</td>
                    <td>${list.mobile}</td>
                    <td>${list.email}</td>
                </tr>
            #end
        </table>
    </body>
</html>

Fourth, 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
 **/
@Controller
public class GenerateController {

    @Value("${filePath}")
    private String filePath;

    @Value("${templatePath}")
    private String templatePath;

    @ResponseBody
    @RequestMapping(value = "/html",method = RequestMethod.GET)
    public String generateHtml(){


        //Generally, here is the list of records found in the database, then traverse the list, generate html one by one, and store the path. Generally, "configuration + table field value" is taken as the storage path.
        // use for instead
        for(int i=1;i<10;i++){

            //Data to be displayed on the page
            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";
    }
}

5. Tools

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 GenerateHtmlUtil {

   static Logger logger = LoggerFactory.getLogger(GenerateHtmlUtil.class);


    /**
     * Generate static HTML files from velocity templates
     * @param fileName the filename of the generated file
     * @param filePath save file location
     * @param templatePath velocity template file path
     * @param params collection
     * @param pageName The variable that needs to be convenient or used on the page, which can be any value
     */
    public  static void generateHtmlByVelocity(String fileName, String filePath,
                                      String templatePath, Object params, String pageName){


        String finalFilePath=filePath+ File.separator+fileName+".html";

        try {

            //Set the way to load the template file, find it under the classpath
            Properties p = new Properties();
            p.put("file.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            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);
        }
    }


}

6. Operation

Browser input localhost:8866/html, display Over

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325041238&siteId=291194637