[英]How to make validations work with @RequestParam
Given Spring Boot 2.6.3
, Hibernate validator 6.2.0.Final
, after running the code below:给定
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;
}
}
If I call http://localhost:8080/test?val=0, it returns 0 and it seems it ignores @Min(10)
part.如果我调用 http://localhost:8080/test?val=0,它返回 0,它似乎忽略了
@Min(10)
部分。
Does anybody know whether it is possible to validate @RequestParam
parameters?有人知道是否可以验证
@RequestParam
参数吗?
I generated a Spring project from https://start.spring.io/ as shown below:我从https://start.spring.io/生成了一个 Spring 项目,如下所示:
I then added the controller code in your question, and an integration test as below:然后我在你的问题中添加了 controller 代码,以及如下的集成测试:
class DemoApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
void testGoodInput() throws Exception {
mockMvc
.perform(MockMvcRequestBuilders.get("/test?val=10"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
void testBadInput() {
Throwable ex = catchThrowable(() -> mockMvc
.perform(MockMvcRequestBuilders.get("/test?val=0"))
.andReturn());
var cause = getViolationExceptionFromCause(ex);
assertThat(cause)
.isInstanceOf(ConstraintViolationException.class);
}
private ConstraintViolationException getViolationExceptionFromCause(Throwable ex) {
if (ex == null || ex instanceof ConstraintViolationException) {
return (ConstraintViolationException) ex;
}
return getViolationExceptionFromCause(ex.getCause());
}
}
This works as expected, val=0
throws a ConstraintViolationException
.这按预期工作,
val=0
抛出ConstraintViolationException
。 It's your turn to prove otherwise.轮到你证明了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.