FreeMarker 无法访问 javabean 的属性

hay*_*uhl 5 templates freemarker javabeans

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

    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试${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]
----------
Run Code Online (Sandbox Code Playgroud)

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

任何提示?

dde*_*any 7

Model 必须是一个公共类才能工作。

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