在SpringBoot应用程序中,我有一个验证器,用于验证除管理员路径模式之外的每个控制器调用的用户
@Configuration
public class CommsCoreWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserValidator()).addPathPatterns("/**").excludePathPatterns("/admin/**");
}
}
以上工作正常,现在我想排除另一个路径的用户验证/ / contents / **但仅针对HEAD方法,我仍然希望为GET,POST / contents / **调用验证器。
我们有办法做到吗
答案 0 :(得分:1)
要使验证器以端点路径和为条件,HttpMethod
可以为验证器添加条件逻辑。由于您使用UserValidator
注册InterceptorRegistry
,因此必须为HandlerInterceptor
,因此类似于此示例......
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
public class UserValidator extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String path = antPathMatcher.extractPathWithinPattern(
(String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE),
request.getPathInfo()
);
if (isExcluded(path, request.getMethod())) {
// skip the validation
} else {
// do whatever your UserValidator usually does
}
return super.preHandle(request, response, handler);
}
private boolean isExcluded(String path, String requestMethod) {
boolean isHeadMethod = HttpMethod.HEAD.matches(requestMethod);
boolean isExcludedPath = EXCLUDED_PATHS.contains(path);
return isHeadMethod && isExcludedPath;
}
}
..允许您控制是否根据HttpMethod
和端点路径应用验证。