在 Spring 中将 POJO 的 public 字段暴露给 FTL

Expose public field of POJO to FTL in Spring

我不知道如何在 Spring 启动时将 POJO 发送到我的模板。

这是我的 POJO 和控制器:

class DebugTest {
    public String field = "Wooowee";
    public String toString() {
        return "testie " + field;
    }
}

@Controller
@RequestMapping("/debug")
public class WebDebugController {

    @RequestMapping(value = "/ftl", method = RequestMethod.GET)
    public ModelAndView ftlTestPage(Model model) {
        DebugTest test = new DebugTest();
        ModelAndView mnv = new ModelAndView("debug");
        mnv.addObject("test", test);
        return mnv;
    }

}

这是我的模板:

HERES THE TEST: ${test}$
HERES THE TEST FIELD: ${test.field}$

这是输出 (GET /debug/ftl):

HERES THE TEST: testie Wooowee$
HERES THE TEST FIELD: FreeMarker template error (DEBUG mode; use RETHROW in production!):
The following has evaluated to null or missing:
==> test.field  [in template "debug.ftl" at line 3, column 25]

[Java stack trace]

根据 JavaBeans 规范,class 本身 (DebugTest) 也必须是 public。此外,默认情况下不会公开字段。定义 getter 方法通常是最好的(可能使用 Lombok),但如果你想使用字段,请这样配置 ObjectWrapper。当你使用 Spring 引导时,我认为你的 application.properites:

中会是这样的
spring.freemarker.settings.objectWrapper=DefaultObjectWrapper(2.3.28, exposeFields = true)