Home > Software design >  How to make validations work with @RequestParam
How to make validations work with @RequestParam

Time:03-09

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?

CodePudding user response:

I generated a Spring project from enter image description here

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.

  • Related