拦截器
你可以注册拦截器来应用于传入的请求,如下例所示:
- Java
- Kotlin
- Xml
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new UserRoleAuthorizationInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(LocaleChangeInterceptor())
registry.addInterceptor(UserRoleAuthorizationInterceptor()).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.handler.UserRoleAuthorizationInterceptor">
<property name="authorizedRoles" value="ROLE_USER"/>
</bean>
</mvc:interceptor>
</mvc:interceptors>
注意
由于拦截器可能与带注释的控制器路径匹配不匹配,因此它们并不理想地适合作为安全层。通常,我们建议使用Spring Security,或者选择一种类似的方法并与Servlet过滤器链集成,并尽可能早地应用。
备注
XML配置将拦截器声明为MappedInterceptor类型的bean,这些拦截器随后会被任何HandlerMappingbean检测到,包括来自其他框架的HandlerMappingbean。相比之下,Java配置只会将拦截器传递给它所管理的HandlerMappingbean。要在Spring MVC和其他框架的HandlerMappingbean中重用相同的拦截器,要么声明MappedInterceptor类型的bean(而无需在Java配置中手动添加它们),要么在Java配置和其他HandlerMappingbean中都进行相同的拦截器配置。