Search code examples
springmodel-view-controllermodelattribute

Sharing modelAttribute between views of different controllers


In my current Spring project (using Thymeleaf), I have this two controllers HomeController and a generic controller extended to all controllers associated to the entities from the model layer.

In the HomeController, i have this modelAttribute mthod:

@ModelAttribute("usuario")
public Usuario usuario() {
  return usuario.findBy("username", SecurityContextHolder.getContext().getAuthentication().getName());
}

Which obviously is acessible by the views mapped in this controller. Is there any way of share this modelAttribute with the views mapped in the other controller?

I read in many places about this RedirectAttributes resource, but I am guessing that only works with redirected views (like modelAndView.setViewName("redirect:welcome");)?


Solution

  • Move the method to a separate class and add the @ControllerAdvice annotation to that class. This way all the model attributes in that class will apply to all controllers in the application.

    If you want to limit the set of controllers where the model attribute will be available you can specify in the @ControllerAdvice annotation that only controllers in specific packages or with specific annotations or implementing specific interfaces should be enhanced.