根据文档,您应该能够将 javabean 传递给 FreeMarker 模板,并且它将能够访问 bean 的 getter。我一直在尝试这样做,但没有任何运气。这是我将 bean 传递给模板的代码。
public class Hello extends HttpServlet {
public static final Logger LOGGER = Logger.getLogger(Hello.class.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(this.getServletContext().getRealPath("/templates")));
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
cfg.setIncompatibleImprovements(new Version(2, 3, 20)); // FreeMarker 2.3.20
final String name = req.getParameter("name");
// This works when model is a Map, but not when it is a bean
Model model = new Model();
model.setUsername(name);
Template template = cfg.getTemplate("hello.ftl");
template.process(model, resp.getWriter());
} catch (TemplateException ex) {
LOGGER.log(Level.SEVERE, "Unexpected template exception", ex);
resp.sendError(500);
}
}
private static class Model {
private String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
}
当我尝试${username}
在模板中访问时,出现以下错误。
The following has evaluated to null or missing:
==> username [in template "hello.ftl" at line 8, column 10]
Tip: If the failing expression is known to be legally null/missing... (snip)
The failing instruction (FTL stack trace):
----------
==> ${username} [in template "hello.ftl" at line 8, column 8]
----------
当我使用地图时,我可以让模板正常工作。我尝试使用各种 TemplateModel 包装器显式包装 Model 对象,但我尝试的任何方法似乎都不起作用。
有什么提示吗?