Mufanu
Mufanu

Reputation: 534

How to call a method for every page?

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.

Upvotes: 4

Views: 3419

Answers (2)

Alexey
Alexey

Reputation: 2582

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.

Upvotes: 12

Joachim Rohde
Joachim Rohde

Reputation: 6045

You could write your own interceptor.

Upvotes: 1

Related Questions