gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:02:42 26 4
gpt4 key购买 nike

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

如何在 thymeleaf 模板的 th:object 指令中访问 generalsecurity 对象?

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

    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} 将在您的 View 中起作用。

但是您应该使用的是 the constructor with 2 arguments ( View 名称和 map 或模型)。

因此,不要使用 new ModelAndView("profile/profile.html", "profile", model) 使用 new ModelAndView("profile/profile.html", model)

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

关于java - 如果我在方法内初始化模型,为什么无法访问模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60046175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com