发布于 2016-10-09 05:24:02 | 111 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Velocity入门教程,程序狗速度看过来!

Velocity 模板引擎

Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。


需求:后台(指管理员后台)上传一个html模板到文件服务器上,前台(商家操作的平台)读取到模板,并填充数据,生成新的vm页面到webapp/WEB-INF/view目录下,用于预览、保存、打印。

最开始的代码:

        @Test
	public void test() throws Exception{
		
		String templateUrl = baseService.getPicServerURL()+"group1/M00/02/1E/wKi0d1NasvaAF6x_AAAdoyBssxg53.html";

		//初始化模板
		Template template = Velocity.getTemplate(templateUrl,"UTF-8");
		//初始化上下文
		VelocityContext context = new VelocityContext();
		//添加数据到上下文中
		context.put("title","我的第一个velocity模板生成页面");
		//生成html页面
		PrintWriter pw = new PrintWriter("webapp/WEB-INF/view/center/dm_manage/test.htm");
		template.merge(context,pw);
		//关闭流
		pw.close();
	}


以上标红色部分为错误的地方:

错误信息:。

出现的原因:我的模板在文件服务器上, Velocity.getTemplate()方法没办法直接解析到服务器上的文件,对于这个问题有三种想法:

1.直接在后台上传文件的时候,上传到web服务器中,弊端:服务器重启后数据会丢失,PASS.

2.用HTMLParser解析html模板,替换里面的值,再生成新的vm页面,弊端:太过复杂,PASS.

3.从服务器上下载html,再写到项目的某个目录中,Velocity.getTemplate()方法就可解析到,WORK。

方案3的完整代码:

//将byte数组写入文件  
    public void createFile(String path, byte[] content) throws IOException {  
        FileOutputStream fos = new FileOutputStream(path);  
        fos.write(content);  
        fos.close();  
    }  
	
	@Test
	public void createNewFile() throws Exception{
		byte[] content = fileService.downloadFile("M00/02/1E/wKi0d1NasvaAF6x_AAAdoyBssxg53.html");
		String path = "src/main/resources/dm-template/wKi0d1NasvaAF6x_AAAdoyBssxg53.html";
		File f = new File(path);
		if(!f.exists()){
			createFile(path, content);
		}
	}
  @Test
	public void test() throws Exception{
		
	  Properties p = new Properties();
		p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "src/main/resources/dm-template/");
		Velocity.init(p);
		
		
		//初始化模板
		Template template = Velocity.getTemplate("wKi0d1NasvaAF6x_AAAdoyBssxg53.html","UTF-8");
		//Template template = ve.getTemplate("group1/M00/02/1E/wKi0d1NasvaAF6x_AAAdoyBssxg53.html","UTF-8");
		//初始化上下文
		VelocityContext context = new VelocityContext();
		//添加数据到上下文中
		context.put("title","我的第一个velocity模板生成页面123test");
		//生成html页面
		PrintWriter pw = new PrintWriter("src/main/webapp/WEB-INF/view/center/dm_manage/test.htm");
		template.merge(context,pw);
		//关闭流
		pw.close();
	}


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务