Velocity 模版引擎的使用

时间:2022-11-24 15:41:34

贴上代码,这是一个工具类,自己为了方便管理信息页面

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import com.***.front.mode.SigningStore;
import com.***.manager.model.TempStores;

/**
* 生成门市联系信息页面
*/
public class CreateStoresShtml {

public static final String DEFAULT_AREA_TYPE = "总部前台"; // 默认显示的区域类型
public static Properties properties = null;
public static VelocityEngine velocityEngine = null;

/***
* 一键生成 shtml 页面
* @param list(所有门市联系方式集合)
* @param vmPath(模版路径)
* @param vmName(模版名称)
* @param shtmlPath(生成页面的路径)
* @throws Exception
*/
public static void createShtmlFnc(List<SigningStore> list,String vmPath,String vmName,String shtmlPath) throws Exception{

if(properties == null){

properties = new Properties();// 初始化参数
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,vmPath);
properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
velocityEngine = new VelocityEngine(); // 实例化一个VelocityEngine对象
}

VelocityContext context = new VelocityContext();
List<TempStores> tempStories = initHeaderStoresData(list);
context.put("tempStories", tempStories);
deleteFile(shtmlPath);// 删除原页面

velocityEngine.init(properties);
Template t = velocityEngine.getTemplate(vmName);

context.put("tempStories", tempStories);
StringWriter writer = new StringWriter();
t.merge(context,writer);
FileOutputStream fos = new FileOutputStream(new File(shtmlPath));
PrintStream ps = new PrintStream(fos, true, "UTF-8");//这里我们就可以设置编码了
ps.print(writer.toString());
ps.flush();
ps.close();
fos.close();
}

/**
* 删除单个文件(旧页面)
* @param sPath 被删除文件的路径
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String sPath) throws Exception{
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}

}
下面贴上模版存放路径

\resources\vm\create_footer_stores.vm

具体信息参考下面模版

<table>
    <tbody>
        <tr>
            <td width="25%" id="stores_cells_1">
                <ul class="stores_a">#foreach( $store1 in $tempStories ) #if($store1.typeName=='总部前台')
                    <li>
                        <h3>总部前台</h3>
                    </li>#foreach( $store in $store1.stores )
                    <li>
                        <p class="phone">电话:${store.landline}</p>
                        <p class="address">${store.address}</p>
                    </li>#end #end #end
                    <li>
                        <h3>分社</h3>
                    </li>#foreach( $store1 in $tempStories ) #if($store1.typeName=='分社') #foreach( $store in $store1.stores )
                    <li>
                        <h4>${store.name}</h4>
                        <p class="phone">电话:${store.landline}</p>
                        <p class="address">${store.address}</p>
                    </li>#end #end #end</ul>
            </td>
        </tr>
    </tbody>
</table>


下面贴上调用方法

/**
* 一键生成门店联系页面
*/
public void createShtmlFnc() {
try {

// 查询所有有效门市的联系方式
List < SigningStore > list = managerSigningStoreService.findAll(new HashMap < String, Object > ());
String webPath = getClass().getResource("/").getFile().toString();
String vmPath = webPath + "/vm"; // VM模版所在文件夹的绝对路径
webPath = webPath.substring(0, webPath.length() - 16); // 项目的绝对路径
String footerPath = webPath + "footer-stores.shtml"; // 底部 门市联系信息页面路径
String footerVmName = "create_footer_stores.vm"; // 底部模版路径
CreateStoresShtml.createShtmlFnc(list, vmPath, footerVmName, footerPath); // 生成头部页面
writeSuccess("操作成功");
} catch(Exception e) {
setExceptionMessage("一键生成门店联系页面时异常!", e);
writeError("系统异常");
}
}