You could create an interceptor which will inject the common data into your model. A nice feature of using interceptors is that you can easily map them to URLs of your choice.
public class CommonDataInjectingInterceptor extends HandlerInterceptorAdapter {
@Autowired
private CommonDataHolder holder;
public void setCommonDataHolder(CommonDataHolder holder) {
this.holder = holder;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (holder != null && modelAndView != null) {
modelAndView.addObject("menu", holder.getMenu());
modelAndView.addObject("footer", holder.getFooter());
}
}
}
Another way could be to create a @ControllerAdvice
which will define generic behavior shared across all controllers. The functionality of such @ControllerAdvice
in Spring 3 is rather basic. Spring 4 introduces new options to control which controllers should be affected by it.
Using a @ControllerAdvice
in combination with @ModelAttribute
can be quite handy. Like Ayub Malik partially explained in his answer.
@ControllerAdvice
public class CommonDataControllerAdvice {
@Autowired
private CommonDataHolder holder;
public void setCommonDataHolder(CommonDataHolder holder) {
this.holder = holder;
}
@ModelAttribute("menu")
public Menu menu() {
return holder.getMenu();
}
@ModelAttribute("footer")
public Footer footer() {
return holder.getFooter();
}
}