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

时间:2021-01-09 06:53:21

  这里面是关于velocity的一些用法,比较基础的使用。愿你生命中有够多的云翳,来造成一个美丽的黄昏。

velocity生成javaBean

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

一、定义一个简单的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(,)$field.substring()##
#end public 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;
}
}

友情链接