給定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引數嗎?
uj5u.com熱心網友回復:

然后我在您的問題中添加了控制器代碼,并進行了如下集成測驗:
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. It's your turn to prove otherwise.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439928.html
