简体   繁体   中英

How to make validations work with @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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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