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