在HandlerInterceptor接口的prehandle()
方法中添加了Interceptor和验证头,然后在WebMvcConfigurer
接口的帮助下添加了此拦截,如果成功,我们会将控件传递给基本URL Controller类。否则它将返回false
,并且不会传递给Controller类。
在Spring WebFlux中我们如何实现相同的目标?在WebFlux中,有类似WebFluxConfigurer
的接口,但是这里没有添加拦截器的方法吗?
还可以借助WebFlux中的RouterFunction
进行路由,但是如何在Spring Mvc中像HandlerInterceptor
这样的公共部分中检查和验证标头呢?**
这是Spring MVC中的以下代码片段:
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
CommonInterceptor CommonInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(CommonInterceptor).addPathPatterns("/api/v1/**");
}
@Component
public class CommonInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(CommonInterceptor.class);
@Autowired
private CommonRequest CommonRequest;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws CommonException {
String tenantContext = request.getHeader(CommonFrameworkConstants.TENANT_CONTEXT);
String authToken = request.getHeader(CommonFrameworkConstants.AUTHORIZATION);
LOGGER.trace("Handling Request for Tenant Context {}", tenantContext);
CommonHeader CommonHeader = new CommonHeader(authToken, tenantContext);
CommonRequest.setCommonHeader(commonHeader);
CommonRequest.setUserName("api");
return true;
}
}