How to validate Spring MVC @PathVariable values?

前端 未结 6 1828
难免孤独
难免孤独 2020-12-09 03:28

For a simple RESTful JSON api implemented in Spring MVC, can I use Bean Validation (JSR-303) to validate the path variables passed into the handler method?

For examp

6条回答
  •  温柔的废话
    2020-12-09 04:16

    Instead of using @PathVariable, you can take advantage of Spring MVC ability to map path variables into a bean:

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @GetMapping("/{id}")
        public void get(@Valid GetDto dto) {
            // dto.getId() is the path variable
        }
    
    }
    

    And the bean contains the actual validation rules:

    @Data
    public class GetDto {
         @Min(1) @Max(99)
         private long id;
    }
    

    Make sure that your path variables ({id}) correspond to the bean fields (id);

提交回复
热议问题