繁体   English   中英

如何使用@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,它返回 0,它似乎忽略了@Min(10)部分。

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

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

在此处输入图像描述

然后我在你的问题中添加了 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());
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM