首页 > 解决方案 > MethodValidationInterceptor 和 @Validated @ModelAttribute

问题描述

我有一个 Spring Boot 2 应用程序,我希望能够使用 Hibernate 验证器验证控制器参数 - 我正在成功使用它。我将所有控制器都注释为@Validated,并且我正在使用对请求参数的验证,就像这样@PathVariable @AssertUuid final String customerId- 到目前为止一切顺利,一切正常。

但是,我也希望能够@ModelAttribute从表单中进行验证。

@Controller
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(path = "/customers")
@Validated
public class CustomerController
{

    private final CustomerFacade customerFacade;

    public CustomerController(
        final CustomerFacade customerFacade
    )
    {
        this.customerFacade = customerFacade;
    }

    @GetMapping("/create")
    public ModelAndView create(
        final AccessToken accessToken
    )
    {
        return new ModelAndView("customer/create")
            .addObject("customer", new CreateCustomerRequest());
    }

    @PostMapping("/create")
    public ModelAndView handleCreate(
        final AccessToken accessToken,
        @Validated @ModelAttribute("customer") final CreateCustomerRequest customerValues,
        final BindingResult validation
    ) throws 
        UserDoesNotHaveAdminAccessException
    {
        if (validation.hasErrors()) {
            return new ModelAndView("customer/create")
                .addObject("customer", customerValues);
        }

        CustomerResult newCustomer = customerFacade.createCustomer(
            accessToken,
            customerValues.getName()
        );

        return new ModelAndView(new RedirectView("..."));
    }

    public static final class CreateCustomerRequest
    {

        @NotNull
        @NotBlank
        private String name;

        public CreateCustomerRequest(final String name)
        {
            this.name = name;
        }

        public CreateCustomerRequest()
        {
        }

        public String getName()
        {
            return name;
        }

    }

}

但这会导致当我发送无效数据时MethodValidationInterceptor抛出。ConstraintViolationException这通常是有道理的,我希望在其他所有情况下都有这种行为,但在这种情况下,如您所见,我想使用BindingResult来处理验证错误——这在处理表单时是必需的。

有没有办法告诉 Spring 不使用 验证这个特定参数MethodValidationInterceptor,因为它已经被活页夹验证了,我想以不同的方式处理它?

我一直在研究 spring 代码,它看起来并不是为了协同工作而设计的。我有一些想法如何解决这个问题:

我会完全错了吗?我错过了什么吗?有没有更好的办法?

标签: javaspringspring-mvcspring-boothibernate-validator

解决方案


我想出了一个可以让我继续工作的解决方案,但我认为这个问题还没有解决。

正如我在原始问题中所暗示的那样,这个方面强制验证@ModelAttribute它何时没有用@Validatedor注释@Valid

这意味着ConstraintViolationException不会因为无效@ModelAttribute而抛出,您可以处理方法体中的错误。

import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.MethodParameter;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@SuppressWarnings({"checkstyle:IllegalThrows"})
@Aspect
public class ControllerModelAttributeAutoValidatingAspect
{

    private final Validator validator;

    public ControllerModelAttributeAutoValidatingAspect(
        final Validator validator
    )
    {
        this.validator = validator;
    }

    @Around("execution(public * ((@org.springframework.web.bind.annotation.RequestMapping *)+).*(..)))")
    public Object proceed(final ProceedingJoinPoint pjp) throws Throwable
    {
        MethodSignature methodSignature = MethodSignature.class.cast(pjp.getSignature());
        List<MethodParameter> methodParameters = getMethodParameters(methodSignature);

        PeekingIterator<MethodParameter> parametersIterator = Iterators.peekingIterator(methodParameters.iterator());
        while (parametersIterator.hasNext()) {
            MethodParameter parameter = parametersIterator.next();
            if (!parameter.hasParameterAnnotation(ModelAttribute.class)) {
                // process only ModelAttribute arguments
                continue;
            }
            if (parameter.hasParameterAnnotation(Validated.class) || parameter.hasParameterAnnotation(Valid.class)) {
                // if the argument is annotated as validated, the binder already validated it
                continue;
            }

            MethodParameter nextParameter = parametersIterator.peek();
            if (!Errors.class.isAssignableFrom(nextParameter.getParameterType())) {
                // the Errors argument has to be right after the  ModelAttribute argument to form a pair
                continue;
            }

            Object target = pjp.getArgs()[methodParameters.indexOf(parameter)];
            Errors errors = Errors.class.cast(pjp.getArgs()[methodParameters.indexOf(nextParameter)]);
            validator.validate(target, errors);
        }

        return pjp.proceed();
    }

    private List<MethodParameter> getMethodParameters(final MethodSignature methodSignature)
    {
        return IntStream.range(0, methodSignature.getParameterNames().length)
            .mapToObj(i -> new MethodParameter(methodSignature.getMethod(), i))
            .collect(Collectors.toList());
    }

}

现在,您可以像往常一样在控制器方法中继续使用验证注释,同时final BindingResult validation按预期工作。

@PostMapping("/create")
public ModelAndView handleCreate(
    final AccessToken accessToken,
    @ModelAttribute("customer") final CreateCustomerRequest customerValues,
    final BindingResult validation
)

推荐阅读