如何使用@RequestParam 进行验证

How to make validations work with @RequestParam

给定 Spring Boot 2.6.3Hibernate 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 ,它 returns 0 并且它似乎忽略了 @Min(10) 部分。

有人知道是否可以验证 @RequestParam 参数吗?

我从 https://start.spring.io/ 生成了一个 Spring 项目,如下所示:

然后我在你的问题中添加了控制器代码,并进行了如下集成测试:

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());
    }
}

这按预期工作,val=0 抛出 ConstraintViolationException。轮到你来证明了。