A
A
Anton Ivanov2020-02-04 09:33:55
Java
Anton Ivanov, 2020-02-04 09:33:55

Why doesn't the call to the model that is defined inside the method work?

Here is an excerpt from the controller:

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 individual DTOs be used in th:object?

I can use them as ${general}and ${secuity}if I change the method like this:

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


In this case, modelthe same class (BindingAwareModelMap), but now everything works. Why?

After all, if I pass as a model, for example, profileGeneralDTO, which is also defined in the method body, then I normally work with its fields in the template.

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
programmerjava, 2020-02-06
@programmerjava

If you are not confused, then it is better to leave it as it works. Are you sure the same method works in both cases?
In general, it is better to use it differently:

@RequestMapping("/subpath")
public String getRequest(Authentication auth, Model model) {
             model.put("key", object);
             model.put("key2", object2);
             return "view.html";  // path to thymeleaf template
}

In general, I can assume that in the first case, your spring does not make a proxy to the model, but in the second it does and for some reason starts working. It is necessary to go into the jungle of documentation. It's easier to do as I wrote

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question