Reputation: 797
I'm developing a web application with Java and Spring Boot. What I would like to do is to add an object into the Model every time a request is received. Let me explain better what I'm doing and why I need it.
The application is an eCommerce and I need every time a page is loaded the number of items inside the cart and the number of notifications a user has got. These information are displayed inside the menu in all the pages of the web app. Right now I'm requesting these information to through an ajax call after the page has been loaded. I would like to automatically add these information inside the Model and render and return all the pages with them already present without making any further request.
I googled it and I found out that a way to solve this problem is to use an Interceptor. I implemented it following this tutorial but the only problem is that preHandle, postHandle and afterCompletion get called not only with the page requests but also with other kind of content like images, videos etc.
@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre Handle method is Calling: " + request.getRequestURI());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Post Handle method is Calling");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
System.out.println("Request and Response is completed");
}
}
Upvotes: 0
Views: 1273
Reputation: 613
When registering your interceptors in WebMvcConfigurerAdapter, you can also define a path pattern to include or exclude.
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new YourInterceptor()).excludePathPatterns("/path/to/your/static/resources/*");
}
Full example is available here : https://www.concretepage.com/spring/spring-mvc/spring-mvc-handlerinterceptor
Upvotes: 1