Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method for every page?

Tags:

spring-mvc

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.

like image 411
Mufanu Avatar asked Dec 11 '22 08:12

Mufanu


1 Answers

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.

like image 72
Alexey Avatar answered Feb 08 '23 07:02

Alexey