Java 为什么可以';如果我在方法内部初始化模型,我是否可以访问它?
ProfileController.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);
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);
}