首页 > 代码库 > web基础----->模板引擎Velocity的使用(二)

web基础----->模板引擎Velocity的使用(二)

  这里面是关于velocity的一些用法,比较基础的使用。

velocity生成javaBean

技术分享

一、定义一个简单的bean类

public class ClassBean {    private String name;    private String comment;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getComment() {        return comment;    }    public void setComment(String comment) {        this.comment = comment;    }}

 

二、生成javabean的velocity代码

private VelocityEngine init() {    VelocityEngine ve = new VelocityEngine();    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());    ve.init();    return ve;}
@Test
public void velocity_test_2() { VelocityEngine ve = init(); Template t = ve.getTemplate("template/ClassVelocity.vm"); VelocityContext ctx = new VelocityContext(); // 数据 List<ClassBean> classBeans = new ArrayList<>(); ClassBean classBean1 = new ClassBean(); classBean1.setName("username"); classBean1.setComment("用户名"); ClassBean classBean2 = new ClassBean(); classBean2.setName("password"); classBean2.setComment("密码"); ClassBean classBean3 = new ClassBean(); classBean3.setName("address"); classBean3.setComment("地址"); classBeans.add(classBean1); classBeans.add(classBean2); classBeans.add(classBean3); ctx.put("className", "Person"); ctx.put("list", classBeans); StringWriter sw = new StringWriter(); t.merge(ctx, sw); System.out.println(sw.toString());}

 

三、ClassVelocity.vm的内容如下

##首字母大写#macro(initUpperCase $field)$field.toUpperCase().substring(0,1)$field.substring(1)###endpublic class $className {#foreach($bean in $list)    private String $bean.getName(); // $bean.getComment()#end#foreach($bean in $list)    #set($filed = $bean.getName())    public String get#initUpperCase($filed)() {        return $filed;    }    public void set#initUpperCase($filed)(String $filed){        this.$filed = $filed;    }#end}

 

四、生成的代码如下:

public class Person {    private String username; // 用户名    private String password; // 密码    private String address; // 地址    public String getUsername() {        return username;    }    public void setUsername(String username){        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password){        this.password = password;    }    public String getAddress() {        return address;    }    public void setAddress(String address){        this.address = address;    }}

 

友情链接

  • 关于velocity的基础使用,参见博客http://www.cnblogs.com/huhx/p/baseusewebvelocity1.html

 

web基础----->模板引擎Velocity的使用(二)