a portion of 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);
}
how can I access general
and security
objects in a th:object
directive at a thymeleaf template?
I can access them as ${general}
and ${secuity}
if I declare model
at the method declaration:
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);
}
the model
has the same BindingAwareModelMap
class, but it works... why?
Both code samples are actually using the wrong constructor for ModelAndView
. You are using the constructor to add a single element to the model. So you are actually adding the Map
you want to use as the model, as an element to the model.
Using ${profile.general}
will work in your views.
However what you should be using is the constructor with 2 arguments (a viewname and a map or model).
So instead of new ModelAndView("profile/profile.html", "profile", model)
use new ModelAndView("profile/profile.html", model)
.
NOTE: The second sample works due to the fact you are adding things to the implicit model and adding that model as a map to the model again. So in that situation both ${profile.general}
and ${general}
will work.
That makes sense, but is there a way to use
${profile.general}
in ath:object
? It works well if I use${profile.general.nickname}
in ath:text
but doesn't work if I use it inth:object
and they try to useth:text="*{nickname}"
As stated don't use the constructor with 3 arguments, use the 2 argument constructor instead. Then you don't need to go through those hoops. Else use
${profile}
as theth:object
andth:field="*{general.nickname}"
. Why would the map need to be the model object (not to be confused with the underlying model!).I understand that and I made it work as I need. The question of "how to use
profile.general
in ath:object
" was more like curiosity. Just to know if it is possible or not