通知控制器方法 *before* @Valid 注释被处理 [英] advise controller method *before* @Valid annotation is handled
问题描述
我正在使用 Spring MVC 4.1 向一个安静的网络服务添加速率限制.
I am adding rate-limiting to a restful webservice using Spring MVC 4.1.
我创建了一个可以应用于控制器方法的 @RateLimited
注释.Spring AOP 方面会拦截对这些方法的调用,并在请求过多时抛出异常:
I created a @RateLimited
annotation that I can apply to controller methods. A Spring AOP aspect intercepts calls to these methods and throws an exception if there have been too many requests:
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RateLimitingAspect {
@Autowired
private RateLimitService rateLimitService;
@Before("execution(* com.example..*.*(.., javax.servlet.ServletRequest+, ..)) " +
"&& @annotation(com.example.RateLimited)")
public void wait(JoinPoint jp) throws Throwable {
ServletRequest request =
Arrays
.stream(jp.getArgs())
.filter(Objects::nonNull)
.filter(arg -> ServletRequest.class.isAssignableFrom(arg.getClass()))
.map(ServletRequest.class::cast)
.findFirst()
.get();
String ip = request.getRemoteAddr();
int secondsToWait = rateLimitService.secondsUntilNextAllowedAttempt(ip);
if (secondsToWait > 0) {
throw new TooManyRequestsException(secondsToWait);
}
}
这一切都很完美,除非 @RateLimited
控制器方法的参数标记为 @Valid
,例如:
This all works perfectly, except when the @RateLimited
controller method has parameters marked as @Valid
, e.g.:
@RateLimited
@RequestMapping(method = RequestMethod.POST)
public HttpEntity<?> createAccount(
HttpServletRequest request,
@Valid @RequestBody CreateAccountRequestDto dto) {
...
}
问题:如果验证失败,验证器抛出MethodArgumentNotValidException
,由@ExceptionHandler
处理,返回错误响应给客户端,永远不会触发我的@Before
从而绕过速率限制.
The problem: if validation fails, the validator throws MethodArgumentNotValidException
, which is handled by an @ExceptionHandler
, which returns an error response to the client, never triggering my @Before
and therefore bypassing the rate-limiting.
如何以优先于参数验证的方式拦截这样的网络请求?
我想过使用 Spring Interceptors 或普通 servlet 过滤器,但它们是通过简单的 url-patterns 映射的,我需要通过 GET/POST/PUT/etc 进行区分.
I've thought of using Spring Interceptors or plain servlet Filters, but they are mapped by simple url-patterns and I need to differentiate by GET/POST/PUT/etc.
推荐答案
我最终放弃了寻找 AOP 解决方案的尝试,而是创建了一个 Spring Interceptor.拦截器 preHandle
处理所有请求并监视处理程序为 @RateLimited
的请求.
I eventually gave up on trying to find an AOP solution and created a Spring Interceptor instead. The interceptor preHandle
s all requests and watches for requests whose handler is @RateLimited
.
@Component
public class RateLimitingInterceptor extends HandlerInterceptorAdapter {
@Autowired
private final RateLimitService rateLimitService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (HandlerMethod.class.isAssignableFrom(handler.getClass())) {
rateLimit(request, (HandlerMethod)handler);
}
return super.preHandle(request, response, handler);
}
private void rateLimit(HttpServletRequest request, HandlerMethod handlerMethod) throws TooManyRequestsException {
if (handlerMethod.getMethodAnnotation(RateLimited.class) != null) {
String ip = request.getRemoteAddr();
int secondsToWait = rateLimitService.secondsUntilNextAllowedInvocation(ip);
if (secondsToWait > 0) {
throw new TooManyRequestsException(secondsToWait);
} else {
rateLimitService.recordInvocation(ip);
}
}
}
}
这篇关于通知控制器方法 *before* @Valid 注释被处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!