通过velecity简单去渲染模板

Java代码

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URISyntaxException;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author guzhen
 * @since 2010-10-27 下午02:47:33
 */
public class Test {
	public static void main(String[] args) throws IOException, URISyntaxException {
	    ApplicationContext context = new ClassPathXmlApplicationContext("test.xml");
	    VelocityEngine  velocityEngine = (VelocityEngine)context.getBean("velocityEngine");
	    Context model = new VelocityContext();
	    model.put("nick", "分销商");
	    model.put("baseInfoUrl", "baidu.com");
	    Test.class.getClassLoader();
	    Writer writer = new FileWriter(new File(ClassLoader.getSystemResource("outPut.txt").toURI()));
	    Template template = null;
	    try {
	         template = velocityEngine.getTemplate("消息.vm", "GBK");
        } catch (ResourceNotFoundException e) {
	        e.printStackTrace();
        } catch (ParseErrorException e) {
	        e.printStackTrace();
        } catch (Exception e) {
	        e.printStackTrace();
        }
        template.merge(model, writer);
        writer.flush();
        writer.close();

	}
}

spring配置为

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">  
  
    <bean id="velocityEngine"  
        class="org.springframework.ui.velocity.VelocityEngineFactoryBean">  
        <property name="resourceLoaderPath" value="classpath:template"></property>  
    </bean>  
  
</beans>  
 

 

其中消息模板为

亲爱的${nick}:
	您在分销平台的供应商权限已经开通,请您按照以下步骤开始网络销售渠道的搭建:
	1、补充企业的基本资料
	2、维护产品信息
	3、发起分销商招募
	4、确定合作的分销商
	5、开始销售
	更多帮助,请查看${baseInfoUrl} 

你可能感兴趣的:(java,apache,spring,bean,velocity)