Spring MVC + Thymeleaf: adding variable to all templates' context

Capuchin picture Capuchin · May 8, 2015 · Viewed 8.1k times · Source

How can I add a "global" variable such as username to be used all around my template context?

Currently I am setting these explicitly to each ModelAndView object in my TemplateController.

Answer

Brian Clozel picture Brian Clozel · May 8, 2015

Several ways to do this.

If you want to add a variable to all views served by a single controller, you can add a @ModelAttribute annotated method - see reference doc.

Note that you can also, using the same @ModelAttribute mechanism, address multiple Controllers at once. For that, you can implement that @ModelAttribute method in a class annotated with @ControllerAdvice - see reference doc.