温馨提示:本文翻译自stackoverflow.com,查看原文请点击:java - Why can't I access model if I initialize it inside method?
java spring Thymeleaf

java - 如果在方法内部初始化模型,为什么不能访问模型?

发布于 2020-04-15 13:00:29

ProfileController.java的一部分:

    public ModelAndView profilePage() {
        ...
        Map<String, Object> model = new BindingAwareModelMap();

        model.put("general", profileGeneralDTO);
        model.put("security", profileSecurityDTO);

        return new ModelAndView("profile/profile.html", "profile", model);
    }

如何在百里香模板指令中访问generalsecurity对象th:object

如果可以在方法声明中声明${general}${secuity}可以访问它们model

    public ModelAndView profilePage(
            @AuthenticationPrincipal User user,
            Map<String, Object> model
    ) {
        ...
//        Map<String, Object> model = new BindingAwareModelMap();

        model.put("general", profileGeneralDTO);
        model.put("security", profileSecurityDTO);

        return new ModelAndView("profile/profile.html", "profile", model);
    }

model具有相同的BindingAwareModelMap类,但它的工作原理......为什么?

查看更多

提问者
Anton Ivanov
被浏览
95
M. Deinum 2020-02-04 18:43

这两个代码示例实际上都使用了错误的构造函数ModelAndView您正在使用构造函数将单个元素添加到模型。因此,您实际上是将Map要用作模型的元素添加到模型中。

使用${profile.general}将适合您的意见。

但是,您应该使用的是带有2个参数的构造函数(一个视图名以及一个映射或模型)。

所以代替new ModelAndView("profile/profile.html", "profile", model)使用new ModelAndView("profile/profile.html", model)

注意:第二个示例的工作是由于您要将事物添加到隐式模型,然后将该模型作为映射再次添加到模型。所以在这种情况下都${profile.general}${general}意志的工作。