在自定义HandlerMethodArgumentResolver中验证PathVariable

时间:2013-12-19 15:52:17

标签: spring validation

我需要在Spring Webapp中验证PathVariable,我需要在许多控制器中执行此操作。我不想通过手动验证来破坏控制器,所以我尝试使用JSR-303验证,但意识到它不支持@PathVariable注释参数。

我的下一个方法是实现一个自己的HandlerMethodArgumentResolver,我尝试以下列方式添加自定义验证:

@Component public class AppDomainIdArgumentResolver implements HandlerMethodArgumentResolver {

[...]

WebDataBinder binder = binderFactory.createBinder(webRequest, null, "enumId");
        arg = binder.convertIfNecessary(arg, paramType, methodParameter);
        if (methodParameter.hasParameterAnnotation(Valid.class)) {
            validateAppDomainId(arg, binder);
        }

[...]

private void validateAppDomainId(Object value, WebDataBinder binder) {
    if (MyEnum.getMyEnum((Integer) value) == null) {
        binder.getBindingResult()
            .addError(new ObjectError("enumId", "no.valid.my.enum"));
    }
}

当我尝试使用BindingResult.getErrors()在控制器中获取错误时,错误为空。如何在HandlerMethodArgumentResolver中添加错误并在控制器中访问它?或者我做的事情基本上是错误的......

0 个答案:

没有答案