How to call a method for every page?

后端 未结 2 900
再見小時候
再見小時候 2021-01-06 05:43

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 o

相关标签:
2条回答
  • 2021-01-06 06:09

    You could write your own interceptor.

    0 讨论(0)
  • 2021-01-06 06:24

    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.

    0 讨论(0)
提交回复
热议问题