Java 自定义请求参数验证器在SpringBoot中不工作
下面是验证文件扩展名的验证器 FileExtensionValidator.java 在pom中添加了以下内容Java 自定义请求参数验证器在SpringBoot中不工作,java,spring,validation,spring-boot,Java,Spring,Validation,Spring Boot,下面是验证文件扩展名的验证器 FileExtensionValidator.java 在pom中添加了以下内容 <dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> <version>1.5.1</ve
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.5.1</version>
</dependency>
通用验证器
通用验证器
1.5.1
使用的弹簧版本:4
我确实在验证逻辑中得到了我的方法。如果我遗漏了任何基本步骤,请让我理解。已经检查过的基本教程都说了相同的步骤
提前感谢。这可能对最初创建此帖子的人没有帮助,但对像我这样面临同样问题的人可能有用 这是因为您需要指定要“验证”的方法。 为此,为了使it工作:
@Valid
@PostMapping("")
fun createStudent( @ValidStudent @RequestBody dto: StudentDTO ) =
studentService.createStudent(dto)
然后,您将在ControllerAdvice处理中管理异常MethodArgumentNotValidException
如果您想对异常抛出部分(我推荐)进行更多控制,您可以选择以下方式:
@PostMapping("")
fun createStudent( @Valid @ValidStudent @RequestBody dto: StudentDTO, errors: Errors) =
if (errors.hasErrors()) throw ResourceNotFoundException(errors.allErrors[0].defaultMessage)
else studentService.createStudent(dto)
然后使用抛出的自定义验证器消息处理所需的异常
这是用Kotlin编写的,但在纯Java中完全相同。
希望这对你有帮助
快乐编码!:) 它以什么方式不起作用?它显示任何错误或只是绕过任何扩展?,您也检查了吗@Rcordoval代码从未进入isValid方法检查更新注释工作绝对正常这是atl-ton
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.5.1</version>
</dependency>
@Valid
@PostMapping("")
fun createStudent( @ValidStudent @RequestBody dto: StudentDTO ) =
studentService.createStudent(dto)
@PostMapping("")
fun createStudent( @Valid @ValidStudent @RequestBody dto: StudentDTO, errors: Errors) =
if (errors.hasErrors()) throw ResourceNotFoundException(errors.allErrors[0].defaultMessage)
else studentService.createStudent(dto)