Warm tip: This article is reproduced from stackoverflow.com, please click
java spring Thymeleaf

Why can't I access model if I initialize it inside method?

发布于 2020-04-15 10:27:37

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?

Questioner
Anton Ivanov
Viewed
87
M. Deinum 2020-02-04 18:43

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.