我正在学习Freemarker框架,我有这个问题。 我可以将自定义对象传递给模板文件吗?我看到这些帖子说他们做了我说的话,但它对我不起作用。
Passing a List of Objects to Freemarker and then Looping
http://freemarker.org/docs/pgui_datamodel_objectWrapper.html
我知道春天可以帮助我,但我想尝试没有它。
我的代码是:
的Servlet
public class servletTest extends HttpServlet {
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig servConfig) throws ServletException {
// TODO Auto-generated method stub
try {
cfg = config.getConfig();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Questa chiamata permette di chiamare il file di configurazione per il
* template
*/
private Configuration cfg;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
SimpleHash root = new SimpleHash();
// expose a "simple" java objects:
root.put("theString", "wombat");
// expose an "arbitrary" java objects:
root.put("theObject", new banquet( "Thinking In Java") );
/* Get the template */
Template template = cfg.getTemplate("banquetsList.ftl");
Writer out_template = new StringWriter();
try {
template.process( root, out_template );
} catch (TemplateException e) {
e.printStackTrace();
}
out.write( out_template.toString() );
}
}
配置文件:
private static void build_config() throws IOException{
cfg = new Configuration();
cfg.setServletContextForTemplateLoading( R.context.get_servletContext(), R.path.get_TEMPLATE() );
DefaultObjectWrapper ObjectWrapper = new DefaultObjectWrapper();
cfg.setObjectWrapper( ObjectWrapper.DEFAULT_WRAPPER );
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
cfg.setIncompatibleImprovements(new Version(2, 3, 20));
}
宴会班:
class banquet{
banquet( /*int code,*/ String title){
//this.code = code;
this.title = title;
}
public String title;
//public int code;
}
模板文件:
<html>
<body>
<h1>
lista di banchetti
</h1>
<div>
</div>
<div>
${theObject.name}
</div>
</body>
我错了或Freemarker有错误?是的我是菜鸟,但这个问题让我开玩笑......
事先感谢所有人:)
我找到了解决方案! 我已经将PUBLIC添加到宴会bean中,我感谢所有人使用setter和getter方法:)