I have multiple views that need one and the same object. Does spring support something for it?
Example:
private LanguageDao dao;
At this point, in every method i need to pass the variable to my view. Every single time...
@GetMapping("/cart")
public ModelAndView showCart() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("show_cart");
modelAndView.addObject("dao", dao); // Get rid of this...
return modelAndView;
}
You can create an interceptor using HandlerInterceptorAdapter
and override postHandle
method in which you'll add needed object to the model. Example below.
@Component
public class ExampleInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
modelAndView.addObject("object", new Object());
}
}
Then you need to add it into registry and specify path pattern(s). If you use WebMvcConfigurerAdapter
you can do it by overriding addInterceptors
method.
@Bean
public ExampleInterceptor exampleInterceptor() {
return new ExampleInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(exampleInterceptor()).addPathPatterns("/*");
}
More on the subject you can find here: http://www.journaldev.com/2676/spring-mvc-interceptor-example-handlerinterceptor-handlerinterceptoradapter