您可以尝试实现一个HandlerInterceptor
,并在preHandle()
中验证此规则。如果请求包含在控制器方法中未定义的查询参数,则只需抛出特定类型的Exception
并配置@ControllerAdvice
来处理此异常。例如:
public class FooHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
Set<String> allowQueryParams = Stream.of(hm.getMethodParameters())
.map(p -> p.getParameterAnnotation(RequestParam.class))
.map(req -> req.value())
.collect(toSet());
for (String currentRequestParamName : request.getParameterMap().keySet()) {
if (!allowQueryParams.contains(currentRequestParamName)) {
throw new FooRestException();
}
}
}
return true;
}
}
使用@ControllerAdvice
来处理异常:
@ControllerAdvice
public class FooExceptionHandler {
@ExceptionHandler(FooRestException.class)
public ResponseEntity<Object> handle(FooRestException ex) {
return new ResponseEntity<>("Some query parameter are not defined", HttpStatus.BAD_REQUEST);
}
}
最后将FooHandlerInterceptor
注册以使用它:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FooHandlerInterceptor());
}
}
我只是给你展示了这个想法。如果你希望这种检查仅适用于特定控制器方法,你可以进一步调整 HandlerInterceptor
中的代码。