Velocity在web项目中生成模板

需求:后台(指管理员后台)上传一个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();
	}

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

错误信息:Unable to find velocity template resources

出现的原因:我的模板在文件服务器上, 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值