Search results
Add a custom Spring MVC Interceptor to your Spring Boot applications
Override one or more methods from the HandlerInterceptor interface:
LayoutThemeInterceptor.java
:
public class LayoutThemeInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
// ...
// Returning false won't execute the postHandle() method and
// won't process other interceptors from the chain
return true;
}
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
// Modify ModelAndView ...
}
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception {
// Cleanup ...
}
// ...
}
Override addInterceptors() method from the WebMvcConfigurer interface in a @Configuration-annoated class to register your Spring MVC interceptors.
WebConfig
:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public HandlerInterceptor layoutThemeInterceptor() {
// ...
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.layoutThemeInterceptor())
.addPathPatterns(...)
// ...
.order(...);
}
// Register other interceptors ...
}