FreeMarker无法访问javabean的属性

时间:2013-08-04 22:34:28

标签: templates javabeans freemarker

根据文档,您应该能够将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]
----------

当我使用Map时,我可以让模板正常工作。我尝试使用各种TemplateModel包装器显式包装Model对象,但我尝试的任何东西似乎都没有用。

任何提示?

1 个答案:

答案 0 :(得分:4)

Model必须是公共课,才能发挥作用。

与该问题无关的其他一些注意事项:使用setServletContextForTemplateLoading代替setDirectoryForTemplateLoading,否则如果从已解压缩的.war运行,您的应用将无效。此外,当然你不能为每个请求重新创建Configuration,但我认为这只是为了这个例子。