攔截器

你可以註冊攔截器以應用於傳入請求,如以下示例所示

  • 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(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,這些 bean 又會被任何 HandlerMapping bean 檢測到,包括來自其他框架的。相比之下,Java 配置僅將攔截器傳遞給它管理的 HandlerMapping bean。要在 Spring MVC 和其他框架的 HandlerMapping bean 之間重用相同的攔截器,可以透過 MVC Java 配置來宣告 MappedInterceptor bean(並且不要在 Java 配置中手動新增它們),或者在 Java 配置和其他 HandlerMapping bean 中配置相同的攔截器。
© . This site is unofficial and not affiliated with VMware.