您可以使用 Spring AOP 并为该请求映射创建一个环绕方面。
创建如下注释:
public @interface RequestParameterOrValidation{
String[] value() default {};
}
然后你可以用它来注释你的请求映射方法:
@GetMapping("/test")
@RequestParameterOrValidation(value={"a", "b"})
public void test(
@RequestParam(value = "a", required = false) String a,
@RequestParam(value = "b", required = false) String b) {
// API code goes here...
}
围绕注释创建一个方面。就像是:
@Aspect
@Component
public class RequestParameterOrValidationAspect {
@Around("@annotation(x.y.z.RequestParameterOrValidation) && execution(public * *(..))")
public Object time(final ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args= joinPoint.getArgs();
MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getStaticPart().getSignature();
Method method = methodSignature.getMethod();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
RequestParameterOrValidation requestParamsOrValidation= method.getAnnotation(RequestParameterOrValidation.class);
String[] params=requestParamsOrValidation.value();
boolean isValid=false;
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation annotation : parameterAnnotations[argIndex]) {
if (!(annotation instanceof RequestParam))
continue;
RequestParam requestParam = (RequestParam) annotation;
if (Arrays.stream(params).anyMatch(requestParam.value()::equals) && args[argIndex]!=null) {
// Atleast one request param exist so its a valid value
return joinPoint.proceed();
}
}
}
throw new IllegalArgumentException("illegal request");
}
}
注意:- 由于请求无效,因此在此处返回 400 BAD REQUEST 将是一个不错的选择。当然,这取决于上下文,但这是一般的经验法则。