我有一个Spring Boot 2应用程序,我希望能够使用Hibernate验证程序来验证 Controller 参数-我正在成功使用它。我将所有 Controller 都注释为@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
验证此特定参数,因为绑定(bind)器已经对其进行了验证,并且我想以不同的方式处理它?我一直在研究Spring代码,但看起来并不是为了协同工作而设计的。我对如何解决这个问题有一些想法:
@Validated
并validator.validate()
-丑陋且危险(您可能会忘记调用它)@ModelAttribute
和BindingResult
并在其中调用 validator ,从而在全局范围内强制进行验证我要彻底解决这个问题吗?我想念什么吗?有没有更好的办法?
最佳答案
我想出了一个可以让我继续工作的解决方案,但是我认为这个问题并没有解决。
正如我在原始问题中所暗示的那样,当未使用@ModelAttribute
或@Validated
进行注释时,此Aspect会强制进行@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());
}
}
现在,您可以像往常一样在 Controller 方法中继续使用验证注释,并且
final BindingResult validation
可以按预期工作。@PostMapping("/create")
public ModelAndView handleCreate(
final AccessToken accessToken,
@ModelAttribute("customer") final CreateCustomerRequest customerValues,
final BindingResult validation
)