Interceptors Configuration using Java or XML
In this section, you will learn about how to configure interceptors using Java or XML.
In Spring MVC, you can configure HandlerInterceptors or WebRequestInterceptors , which can be applied to all incoming requests or confined to particular URL patterns.
Given below sample code for registering interceptors in Java :
@Configuration
@EnableWebMvc
public class MyAppWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleInterceptor());
registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
}
}
You can do the same in XML using the <mvc:interceptor> as follows :
<mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> <mvc:interceptor> <mapping path="/**"/> <exclude-mapping path="/admin/**"/> <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" /> </mvc:interceptor> <mvc:interceptor> <mapping path="/secure/*"/> <bean class="org.example.SecurityInterceptor" /> </mvc:interceptor> </mvc:interceptors>