How to call a method for every page?

戏子无情 提交于 2020-01-11 03:09:07

问题


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.


回答1:


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.




回答2:


You could write your own interceptor.



来源:https://stackoverflow.com/questions/20676949/how-to-call-a-method-for-every-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!