我正在学习 Freemarker 框架,我有这个问题。我可以将自定义对象传递给模板文件吗?我看到这些帖子说他们照我说的做,但对我不起作用。
http://freemarker.org/docs/pgui_datamodel_objectWrapper.html
我知道春天可以帮助我,但我想尝试没有它。
我的代码是这样的:
小服务程序:
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 方法,谢谢大家:)