为什么我不能在Spring MVC中使用Valid参数和RequestParam?

sof*_*fs1 10 spring spring-mvc bean-validation

例:

public String getStudentResult(@RequestParam(value = "regNo", required = true) String regNo, ModelMap model){
Run Code Online (Sandbox Code Playgroud)

如何在此处使用@valid作为regNo参数?

Gui*_* He 13

迟到的答案.我最近遇到这个问题并找到了解决方案.你可以这样做,首先注册一个bean MethodValidationPostProcessor:

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
}
Run Code Online (Sandbox Code Playgroud)

然后添加@Validated到控制器的类型级别:

@RestController
@Validated
public class FooController {
    @RequestMapping("/email")
    public Map<String, Object> validate(@Email(message="??????email??") @RequestParam String email){
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("email", email);
    return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果用户请求了无效的电子邮件地址,ConstraintViolationException则会抛出.你可以抓住它:

@ControllerAdvice
public class AmazonExceptionHandler {

@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleValidationException(ConstraintViolationException e){
    for(ConstraintViolation<?> s:e.getConstraintViolations()){
        return s.getInvalidValue()+": "+s.getMessage();
    }
    return "???????";
}
Run Code Online (Sandbox Code Playgroud)

}

你可以在这里查看我的演示


San*_*eep 4

@Valid可用于验证bean。我还没有看到它用于单个字符串参数。它还需要配置一个验证器。

@Valid 注释是标准 JSR-303 Bean 验证 API 的一部分,而不是特定于 Spring 的构造。只要配置了适当的验证器,Spring MVC 就会在绑定后验证 @Valid 对象。

参考:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html