velocity把字符串当做模板
velocity把字符串当做模板方式一:(这种方式网上有很多)
public static void main(String[] args) throws Exception {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();
// 取得velocity的模版内容, 模板内容来自字符传
String content = "";
content += "Welcome $name to Javayou.com! ";
content += " today is $date.";
// 取得velocity的上下文context
VelocityContext context = new VelocityContext();
// 把数据填入上下文
context.put("name", "javaboy2012");
context.put("date", (new Date()).toString());
// 输出流
StringWriter writer = new StringWriter();
// 转换输出
ve.evaluate(context, writer, "", content); // 关键方法
System.out.println(writer.toString());
}
velocity把字符串当做模板方式二:这种方式不常见,个人感觉麻烦,但是模板放数据库的方便管理与维护
1.主方法
Properties p = new Properties();
//p.setProperty("input.encoding", "UTF-8");
//p.setProperty("output.encoding", "UTF-8");
//p.setProperty("resource.loader", "srl");
p.setProperty("resource.loader", "string");
p.setProperty("string.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.StringResourceLoader");
p.setProperty("string.resource.loader.repository.class",
"com.lifeng.pcis.StringTemplateRepository"); //这是自定义的获取模板实现类
try {
Velocity.init(p);
} catch (Exception e) {
Velocity.init(p);
}
Template template = Velocity.getTemplate(draftsman.getEdrType() + ","
+ draftsman.getProdNo() + "," + draftsman.getReasonOrBundleCode(), "UTF-8");
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("draftsman", draftsman);
StringWriter sw = new StringWriter();
template.merge(velocityContext, sw);
logger.debug(sw.toString());
2.StringTemplateRepository实现类
public class EndorseWordingTemplateRepository implements StringResourceRepository {
public String getEncoding() {
// TODO Auto-generated method stub
return "UTF-8";
}
public StringResource getStringResource(String name) {
// TODO Auto-generated method stub
String nameSects[] = name.split(",");
try {
String str = "";//这里可以根据传进来的参数name,查询模板(模板可以在数据库或文件中)
return new StringResource(str, this.getEncoding());
} catch (BusinessServiceException e) {
throw new ResourceNotFoundException("获取模板异常");
}
}
public void putStringResource(String arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
}
public void putStringResource(String arg0, String arg1) {
// TODO Auto-generated method stub
}
public void removeStringResource(String arg0) {
// TODO Auto-generated method stub
}
public void setEncoding(String arg0) {
// TODO Auto-generated method stub
}
}
还没有评论,来说两句吧...