freemarker输出多对一语法
发布网友
发布时间:2022-04-22 03:43
我来回答
共2个回答
热心网友
时间:2022-04-21 13:07
老师类
public class Teacher {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
学生类
public class Students {
private Teacher teacher;
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
测试代码
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
public class Test {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
Configuration cfg = new Configuration();
cfg.setObjectWrapper(new DefaultObjectWrapper());
Reader reader = new StringReader("teacher's name is :${students.teacher.name}");
Template template = new Template("stringTemplate", reader, cfg);
Writer out = new StringWriter();
Map<String, Object> map = new HashMap<String, Object>();
Students students = new Students();
Teacher teacher = new Teacher();
teacher.setName("张三");
students.setTeacher(teacher);
map.put("students", students);
template.process(map, out);
out.flush();
out.close();
System.out.println(out);
}
}
不知道你的代码是怎么写,我按照我的理解给你写了个例子,你自己看看吧。
热心网友
时间:2022-04-21 14:25
private Teacher teacherid;????你的变量名是teacherid,
可以改students.teacherid.name或定义private Teacher teacher;