I'm writing an application using Spring MVC. I have a method that returns values from a database. And I want to display these values in the site's header (which is shown on all pages). How I can do this?
I need to call this method in every controller.
Declare a class with @ControllerAdvice
annotation, then declare a method with @ModelAttribute
annotation. For example:
@ControllerAdvice
public class GlobalControllerAdvice {
@ModelAttribute
public void myMethod(Model model) {
Object myValues = // obtain your data from DB here...
model.addAttribute("myDbValues", myValues);
}
}
Spring MVC will invoke this method before each method in each MVC controller. You will be able to use the myDbValues
attribute in all pages.
The @ControllerAdvice
class should be in the same Java namespace where all your MVC controllers are (to make sure Spring can detect it automatically).
See the Spring Reference for more details on @ControllerAdvice
and @ModelAttribute
annotations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With