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);
}
如何在百里香模板的指令中访问general
和security
对象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
类,但它的工作原理......为什么?
这两个代码示例实际上都使用了错误的构造函数ModelAndView
。您正在使用构造函数将单个元素添加到模型。因此,您实际上是将Map
要用作模型的元素添加到模型中。
使用${profile.general}
将适合您的意见。
但是,您应该使用的是带有2个参数的构造函数(一个视图名以及一个映射或模型)。
所以代替new ModelAndView("profile/profile.html", "profile", model)
使用new ModelAndView("profile/profile.html", model)
。
注意:第二个示例的工作是由于您要将事物添加到隐式模型,然后将该模型作为映射再次添加到模型。所以在这种情况下都${profile.general}
和${general}
意志的工作。
这是有道理的,但有使用方法
${profile.general}
的th:object
?如果我${profile.general.nickname}
在a中使用它会很好,th:text
但是如果我在in中使用它却无法使用,th:object
而他们尝试使用th:text="*{nickname}"
如上所述,不要将构造函数与3个参数一起使用,而应使用2个参数的构造函数。然后,您无需经历那些麻烦。其他
${profile}
用作th:object
和th:field="*{general.nickname}"
。为什么地图需要成为模型对象(不要与基础模型混淆!)。我了解这一点,并根据需要使它起作用。“如何
profile.general
在th:object
”中使用的问题更像是好奇心。只知道是否可能