如何使用 @RequestParam 进行验证
给定 Spring Boot 2.6.3
、Hibernate validator 6.2.0.Final
,运行以下代码后:
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.Min;
@RestController
@Validated
public class TestController {
@GetMapping("/test")
public Integer test( @Min(10) @RequestParam Integer val) {
return val;
}
}
如果我调用 http://localhost:8080/test?val= 0 ,它返回 0 并且似乎忽略了 @Min(10)
部分。
有谁知道是否可以验证 @RequestParam
参数?
Given Spring Boot 2.6.3
, Hibernate validator 6.2.0.Final
, after running the code below:
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.Min;
@RestController
@Validated
public class TestController {
@GetMapping("/test")
public Integer test( @Min(10) @RequestParam Integer val) {
return val;
}
}
If I call http://localhost:8080/test?val=0 , it returns 0 and it seems it ignores @Min(10)
part.
Does anybody know whether it is possible to validate @RequestParam
parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我从 https://start.spring.io/ 生成了一个 Spring 项目,如下所示:
然后我将控制器代码添加到您的问题,以及如下集成测试:
这按预期工作,
val=0
抛出ConstraintViolationException
。现在轮到你证明事实并非如此了。I generated a Spring project from https://start.spring.io/ as shown below:
I then added the controller code in your question, and an integration test as below:
This works as expected,
val=0
throws aConstraintViolationException
. It's your turn to prove otherwise.