velocity把字符串当做模板

骑猪看日落 2022-09-26 01:49 331阅读 0赞



velocity把字符串当做模板方式一:(这种方式网上有很多)

  1. public static void main(String[] args) throws Exception {
  2. // 初始化并取得Velocity引擎
  3. VelocityEngine ve = new VelocityEngine();
  4. ve.init();
  5. // 取得velocity的模版内容, 模板内容来自字符传
  6. String content = "";
  7. content += "Welcome $name to Javayou.com! ";
  8. content += " today is $date.";
  9. // 取得velocity的上下文context
  10. VelocityContext context = new VelocityContext();
  11. // 把数据填入上下文
  12. context.put("name", "javaboy2012");
  13. context.put("date", (new Date()).toString());
  14. // 输出流
  15. StringWriter writer = new StringWriter();
  16. // 转换输出
  17. ve.evaluate(context, writer, "", content); // 关键方法
  18. System.out.println(writer.toString());
  19. }

velocity把字符串当做模板方式二:这种方式不常见,个人感觉麻烦,但是模板放数据库的方便管理与维护

1.主方法

  1. Properties p = new Properties();
  2. //p.setProperty("input.encoding", "UTF-8");
  3. //p.setProperty("output.encoding", "UTF-8");
  4. //p.setProperty("resource.loader", "srl");
  5. p.setProperty("resource.loader", "string");
  6. p.setProperty("string.resource.loader.class",
  7. "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
  8. p.setProperty("string.resource.loader.repository.class",
  9. "com.lifeng.pcis.StringTemplateRepository"); //这是自定义的获取模板实现类
  10. try {
  11. Velocity.init(p);
  12. } catch (Exception e) {
  13. Velocity.init(p);
  14. }
  15. Template template = Velocity.getTemplate(draftsman.getEdrType() + ","
  16. + draftsman.getProdNo() + "," + draftsman.getReasonOrBundleCode(), "UTF-8");
  17. VelocityContext velocityContext = new VelocityContext();
  18. velocityContext.put("draftsman", draftsman);
  19. StringWriter sw = new StringWriter();
  20. template.merge(velocityContext, sw);
  21. logger.debug(sw.toString());

2.StringTemplateRepository实现类

  1. public class EndorseWordingTemplateRepository implements StringResourceRepository {
  2. public String getEncoding() {
  3. // TODO Auto-generated method stub
  4. return "UTF-8";
  5. }
  6. public StringResource getStringResource(String name) {
  7. // TODO Auto-generated method stub
  8. String nameSects[] = name.split(",");
  9. try {
  10. String str = "";//这里可以根据传进来的参数name,查询模板(模板可以在数据库或文件中)
  11. return new StringResource(str, this.getEncoding());
  12. } catch (BusinessServiceException e) {
  13. throw new ResourceNotFoundException("获取模板异常");
  14. }
  15. }
  16. public void putStringResource(String arg0, String arg1, String arg2) {
  17. // TODO Auto-generated method stub
  18. }
  19. public void putStringResource(String arg0, String arg1) {
  20. // TODO Auto-generated method stub
  21. }
  22. public void removeStringResource(String arg0) {
  23. // TODO Auto-generated method stub
  24. }
  25. public void setEncoding(String arg0) {
  26. // TODO Auto-generated method stub
  27. }
  28. }

发表评论

表情:
评论列表 (有 0 条评论,331人围观)

还没有评论,来说两句吧...

相关阅读