您可以使用以下两种方式之一:
- 使用 Spring AOP 并为该请求创建一个环绕方面
映射
- 使用 HandlerInterceptorAdapter 拦截对给定 URI 的请求
1.使用 Spring AOP
创建如下注释:
public @interface RequestParameterPairValidation {
}
然后你可以用它来注释你的请求映射方法:
@GetMapping("/test")
@RequestParameterPairValidation
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 RequestParameterPairValidationAspect {
@Around("@annotation(x.y.z.RequestParameterPairValidation) && execution(public * *(..))")
public Object time(final ProceedingJoinPoint joinPoint) throws Throwable {
Object[] requestMappingArgs = joinPoint.getArgs();
String a = (String) requestMappingArgs[0];
String b = (String) requestMappingArgs[1];
boolean requestIsValid = //... execute validation logic here
if (requestIsValid) {
return joinPoint.proceed();
} else {
throw new IllegalArgumentException("illegal request");
}
}
}
请注意,由于请求无效,因此在此处返回 400 BAD REQUEST 是一个不错的选择。当然,这取决于上下文,但这是一般的经验法则。
2。使用 HandlerInterceptorAdapter
创建一个新的拦截器映射到您想要的 URI(在本例中为 /test):
@Configuration
public class CustomInterceptor extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(new CustomRequestParameterPairInterceptor())
.addPathPatterns("/test");
}
}
在自定义拦截器中定义验证逻辑:
public class CustomRequestParameterPairInterceptor extends HandlerInterceptorAdapter {
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object obj, Exception exception) throws Exception {
}
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object obj, ModelAndView modelAndView) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
// Run your validation logic here
}
}
我会说第二个选项是最好的选项,因为您可以直接控制请求的答案。在这种情况下,它可能是 400 BAD REQUEST,或任何其他对您的情况更有意义的东西。