Interceptors

您可以注册拦截器以应用于传入请求,如下例所示:

You can register interceptors to apply to incoming requests, as the following example shows:

  • Java

  • Kotlin

  • Xml

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new LocaleChangeInterceptor());
	}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {

	override fun addInterceptors(registry: InterceptorRegistry) {
		registry.addInterceptor(LocaleChangeInterceptor())
		registry.addInterceptor(ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**")
	}
}
<mvc:interceptors>
	<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
	<mvc:interceptor>
		<mvc:mapping path="/**"/>
		<mvc:exclude-mapping path="/admin/**"/>
		<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
	</mvc:interceptor>
</mvc:interceptors>

由于可能与带注释的控制器路径匹配不匹配,因此拦截器不适合作为安全层。通常,我们建议使用 Spring Security,或将类似的方法与 Servlet 过滤器链集成并尽早应用。

Interceptors are not ideally suited as a security layer due to the potential for a mismatch with annotated controller path matching. Generally, we recommend using Spring Security, or alternatively a similar approach integrated with the Servlet filter chain, and applied as early as possible.

XML 配置把拦截器声明为 MappedInterceptor Bean,而那些拦截器反过来被任何 HandlerMapping Bean 检测到,包括来自其他框架的那些拦截器。相比之下,Java 配置仅把拦截器传递给它管理的 HandlerMapping Bean。为了在 MVC Java 配置中跨 Spring MVC 和其他框架 HandlerMapping Bean 重用相同的拦截器,要么声明 MappedInterceptor Bean(不要手动把它们添加到 Java 配置中),要么同时在 Java 配置中和在其他 HandlerMapping Bean 中配置相同的拦截器。

The XML config declares interceptors as MappedInterceptor beans, and those are in turn detected by any HandlerMapping bean, including those from other frameworks. By contrast, the Java config passes interceptors only to the HandlerMapping beans it manages. To re-use the same interceptors across Spring MVC and other framework HandlerMapping beans with the MVC Java config, either declare MappedInterceptor beans (and don’t manually add them in the Java config), or configure the same interceptors in both the Java config and in other HandlerMapping beans.