Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么可以';如果我在方法内部初始化模型,我是否可以访问它?_Java_Spring_Thymeleaf - Fatal编程技术网

Java 为什么可以';如果我在方法内部初始化模型,我是否可以访问它?

Java 为什么可以';如果我在方法内部初始化模型,我是否可以访问它?,java,spring,thymeleaf,Java,Spring,Thymeleaf,ProfileController.java的一部分: public ModelAndView profilePage() { ... Map<String, Object> model = new BindingAwareModelMap(); model.put("general", profileGeneralDTO); model.put("security", profileSecurityDTO);

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);
    }

model
具有相同的
BindingAwareModelMap
类,但它可以工作。。。为什么?

两个代码示例实际上都使用了错误的构造函数。您正在使用构造函数向模型中添加单个元素。因此,您实际上是在添加要用作模型的
映射
,作为模型的一个元素

使用
${profile.general}
将在您的视图中起作用

但是,您应该使用的是(视图名称和贴图或模型)

因此,不要使用
newmodelandview(“profile/profile.html”,“profile”,model)
而使用
newmodelandview(“profile/profile.html”,model)


注意:第二个示例之所以有效,是因为您正在向隐式模型添加内容,并再次将该模型作为映射添加到模型中。因此在这种情况下,
${profile.general}
${general}
都可以工作

在第二次使用ProfileGeneralTo时,您根本不使用模型映射对不起,这是一个错误的复制粘贴。。。当然,在第二个代码块中也是“model”。因为您使用了错误的
ModelAndView
构造函数。您使用的是向模型传递模型属性的模型。因此,您正在将键
profile
下的贴图添加到模型中。使用
profile.general
有效。相反,您希望使用
newmodelandview(newmodelandview(“profile/profile.html”,model)
。不同之处在于,第二个模型中既有
profile.general
又有
general
。谢谢。但是使用${profile.general}适用于所有指令,除非我尝试在th:object=”这样的结构中使用它。”${profile.general}->th:field=“*{昵称}”这是有道理的,但是有没有办法在
th:object
中使用
${profile.general.nickname}
?如果我在
th:text
中使用
${profile.general.nickname}
,效果很好,但是如果我在
th:object
中使用
th:object
并且他们试图使用
th:text=“*{昵称}
如上所述,不要使用带有3个参数的构造函数,而是使用2个参数的构造函数。这样你就不需要经历这些困难。否则,使用
${profile}
作为
th:object
th:field=“*{general.昵称}”
。为什么映射需要是模型对象(不要与底层模型混淆!)我理解这一点,并根据需要使其工作。“如何在
th:object
中使用
profile.general
”更像是好奇。只是想知道这是否可能
    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);
    }